Thursday, December 22, 2016

JavaScript Evolution ECMAScript 6 - Maps

Maps are a data structure composed of a collection of key/value pairs. they are very useful to store simple data such as property value. They are present in many programming languages such a Scala.

The key in Map must be unique and associated with only 1 value.

key ---> value
key ---> value
key ---> value

JavaScript developer explores to Map thru Object. It is possible to use Object as Map, but there is some issue with that. The biggest issue of using Object as Map is the key always converted to String.

Let's take a look at the below example:
let user1 = {name: "Sam"};
let user2 = {name: "Tyler"};

let totalReplies = {};
totalReplies [user1] = 5;
totalReplies [user2] = 42;

console.log(totalReplies [user1]); // Return 42
console.log(totalReplies [user2]); // Return 42
Although we assign 2 different value to the key, the last assign overwrites the previous value because JavaScript converts the Object to String - [object, object].

To get around this issue, we should use the Map. Any value may be used as either a key or a value are not converted to String. Let change totalReplied to a Map.
let user1 = {name: "Sam"};
let user2 = {name: "Tyler"};

let totalReplies = new Map();
totalReplies.set(user1, 5);
totalReplies.set(user2, 42);

console.log(totalReplies.get(user1)); // Return 5
console.log(totalReplies.get(user2)); // Return 42
As you can see, the 2 value assigned to different Object key as expected.

We use get() and set() methods to access the value in Map. To delete a value in Map, you can use delete() method.
totalReplies.delete(user1);
The map is iteratable, so they can be used in the for...of loop. Each ran of the loop returns a [key, value] pair for an entry in the Map.
let mapSettings = new Map();
mapSettings.set("user", "Sam");
mapSettings.set("topic", "ES2015");

for (let [key, value] of mapSettings) {
  console.log(`${key} = ${value}`);
}

// Return
// user = Sam
// topic = ES2015

No comments:

Post a Comment