Adblocker detected! Please consider whitelist or disable this site.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

To keep the site operating, we need funding, and practically all of it comes from internet advertising.

If you still want to continue, Please add techgeeknext.com to your ad blocking whitelist or disable your adblocking software.

×
Typescript Map, Set and Weak Collections (2024) | TechGeekNxt >>


Typescript Map, Set and Weak Collections (2024)

  1. TypeScript Map
  2. TypeScript Set
  3. TypeScript WeakSet
  4. TypeScript WeakMap
Map and set have been introduced in ES2015 to two new primitives. They are both iterable, so you can loop through them like an array. Why are you going to use them? Using these basics in other languages, they provide a more structured way to assign and access data and can appear familiar.

Lets explore the different collections we can use in TypeScript. Like most popular programming languages(Java, C#, Python), Angular TypeScript also provide data collections :

TypeScript Map Collections :

Coming from Full stack world, if you are searching for the JavaScript HashMap then TypeScript has Map collection.

Map is a data structure, used to store key value pair of any type like any other languages and remembers the original order of insertion of the keys.

  • Map is a class that can be instantiated with or without values
  • The map works better when many add and delete, This data structures is optimized for fast retrieval, it uses the hashing function below.
  • When an element is added, it preserves the order. This could be an advantage, as the map is naturally iterable.
  • A map performs better with a large set of data
  • A map's key is not limited to a number or a string for a key.
  • In Map, Key should not be duplicate, while values can be duplicate.

Key functions provided by the Map :

  • set(key: K, value?: V): // method to add entries.
  • get(key: K) // method to retrieve an entry.
  • size // to return size of Map.
  • has(Key : K): // Returns a boolean asserting by key.
  • delete(key: K) //method to delete an entry.
  • clear() // Removes all key-value pairs from Map.

Let's see some example of how to use Map :



    let map1 = new Map(); // Key any, value any
    let myMap = new Map(); // Key string, value number
    myMap.set("A",101);
    myMap.set("B",102);
    myMap.set("C",103);
    myMap.size;  // output is 3
    myMap.get("B"); //output is 102

    //Iterate map keys
    for (let item of myMap.keys()) {
        console.log(item);                   //output is A B C
    }

    //Iterate map values
    for (let item of myMap.values()) {
        console.log(item);                 //101 102 103
    }

    //Iterate map entries
    for (let item of myMap.entries()) {
        console.log(item[0], item[1]);    //"A" 101"B" 102"C" 103
    }

    //Using object destructuring
    for (let [key, value] of myMap) {
        console.log(key, value);            //"A" 101"B" 102"C" 103
    }

    // item B will get deleted and it will return true flag as output
    myMap.delete("B")

    // it will clear all entries of map
    myMap.clear();
    

The difference between our Dictionary class and the ES6 Map class is that the values and key methods return an Iterator (which you studied in Chapter 2, Arrays) instead of a value or key array. A further difference is that the number of values the map stores is returned by a size method. A property named size is available in the ES6 Map class.

TypeScript ForEach :

Array also provide another method Array.prototype.forEach(), the forEach() method does not return anything (undefined). It simply calls the required function on each element in your array This callback is allowed to change the calling array

let arr = [1, 2, 3, 4];

arr.forEach((num, index) => {
    arr[index] = num * 2;
});

// Output will be
// arr = [2, 4, 6, 8]

TypeScript Map vs ForEach

  • map() may be preferable if you favor functional programming.
  • forEach() affects and changes our original Array
  • While map() returns an entirely new Array - thus leaving the original array unchanged.
  • map() is faster than forEach when changing or altering data. You can also chaining on other cool methods like ( map(), filter(), reduce(), etc.)
  • forEach() may be preferable when you want to just do something more with it - like saving it to a database or logging it out, etc

TypeScript Set Collections :

The Set object lets you store unique values of any type, whether primitive values or object references

One difference between TypeScript Sets and other languages is, You can iterate its elements in insertion order (so order matters in TypeScript)

Here is the exmple of how to use Set:


    var mySet = new Set();

    // add element to mySet
    mySet.add(20);
    mySet.add(50);
    mySet.add("test text");

    var emp = {name: "Sam"};
    mySet.add(emp);

    // validate
    mySet.has(50); // true
    mySet.has(60); // false, 60 has not been added to the mySet
    mySet.has("test Text".toLowerCase()); // true
    mySet.has(emp); // true

    //operations
    mySet.size; // 4
    mySet.delete(50); // removes 50 from the mySet
    mySet.has(50);    // false, 50 has been removed

    mySet.size; // 3, we just removed one value

    // iterate over items in set in different ways :
    // logs the items in the order: 20,"test text" 

    for (let item of mySet)
        console.log(item);

    for (let item of mySet.keys())
        console.log(item);

    for (let item of mySet.values())
        console.log(item);

    //(key and value are the same here)
    for (let [key, value] of mySet.entries())
        console.log(key);


    // Iterate set entries with forEach
    mySet.forEach(function(value) {
        console.log(value);
    });
                    

TypeScript Weak Collections :

In addition to the two new data structures Set and Map, ES6 also implemented a weak version of these classes: WeakMap and WeakSet.

Typescript has weak collections called WeakMap and WeakSet. These ES6 collections called weak because they allow for objects which are no longer needed to be cleared from memory.

While Map and Set references to strong collections as they can get expensive if maps/sets reference large objects that are no longer needed, even when the DOM elements have already been removed. They will not allow for garbage collection.

Essentially, the only distinction between the Map or Set groups and their Weak variants is:
  • You can only use Objects as a key
  • The WeakSet or WeakMap classes do not have entries, keys, and value methods
  • WeakSet and WeakMap are better at performance than Set and Map because they are weakly typed (using the object as a key), there is no clear reference to the keys. This behavior helps the JavaScript garbage collector to clean or set the entire entry from the map.

The following is an example of what we can do with the WeakMap class:

var map = new WeakMap();

var ob1 = {name:'Sam'}, //{1} 
    ob2 = {name:'John'},
    ob3 = {name:'Roy'};

map.set(ob1, 'sam@email.com'); //{2} 
map.set(ob2, 'johndeep@email.com');
map.set(ob3, 'roy@email.com');

console.log(map.has(ob1));  //{3} outputs true 
console.log(map.get(ob3)); //{4} outputs roy@email.com 
map.delete(ob2); //{5} 

We can still use the WeakMap class set method. However, since it does not allow us to use String or any other primitive data type (numeric, String, or Boolean values), we need to convert the name to an object (lines{ 1} and{ 2}). To check the value (line{ 3}), retrieve the value (line{ 4}), and also delete the value (line{ 5}), we need to move the object generated as a key.

The same logic applies to the WeakSet class.

Next we will see RxJS concatMap
















Recommendation for Top Popular Post :