Saturday, 10 October 2020

Javascript: Map and Set

Now we’ve learned about the following complex data structures:

  • Objects for storing keyed collections.
  • Arrays for storing ordered collections.

But that’s not enough for real life. That’s why Map and Set also exist.

 Map 

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

Methods and properties are:

  1. new Map() – creates the map.
  2. map.set(key, value) – stores the value by the key.
  3. map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  4. map.has(key) – returns true if the key exists, false otherwise.
  5. map.delete(key) – removes the value by the key.
  6. map.clear() – removes everything from the map.
  7. map.size – returns the current element count.

For instance:

let map = new Map();

map.set('1''str1');   // a string key
map.set(1'num1');     // a numeric key
map.set(true'bool1'); // a boolean key


Map can also use objects as keys.

let john = { name: "John" };
let map = new Map();

map.set(john'str1');   // a string key


Every map.set call returns the map itself, so we can “chain” the calls:

map.set('1''str1')
  .set(1'num1')
  .set(true'bool1');


Iteration over Map

For looping over a map, there are 3 methods:

  • map.keys() – returns an iterable for keys,
  • map.values() – returns an iterable for values,
  • map.entries() – returns an iterable for entries [key, value],

let recipeMap = new Map([
    ['cucumber'500],
    ['tomatoes'350],
    ['onion',    50]
  ]);
  
  // iterate over keys (vegetables)
  for (let vegetable of recipeMap.keys()) {
    alert(vegetable); // cucumber, tomatoes, onion
  }
  
  // iterate over values (amounts)
  for (let amount of recipeMap.values()) {
    alert(amount); // 500, 350, 50
  }
  
  // iterate over [key, value] entries
  for (let entry of recipeMap) { // the same as of recipeMap.entries()
    alert(entry); // cucumber,500 (and so on)
  }

// iterate with foreach
recipeMap.forEach(function(valuekey) {
    console.log(key + ' -> ' + value);
  });


Set 

A Set is a special type collection – “set of values” (without keys), where each value may occur only once.

Its main methods are:

  1. new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  2. set.add(value) – adds a value, returns the set itself.
  3. set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  4. set.has(value) – returns true if the value exists in the set, otherwise false.
  5. set.clear() – removes everything from the set.
  6. set.size – is the elements count.

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason each value appears in a Set only once.

For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.

Set is just the right thing for that:

let set = new Set();

let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);

// set keeps only unique values
alertset.size ); // 3

for (let user of set) {
  alert(user.name); // John (then Pete and Mary)
}

The alternative to Set could be an array of users, and the code to check for duplicates on every insertion using arr.find. But the performance would be much worse, because this method walks through the whole array checking every element. Set is much better optimized internally for uniqueness checks.








0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives