Thursday, August 30, 2018

ES6 - Map Class Tutorials with Javascript Examples | Typescript Map Examples

Es6 Map Class

The map is a one of the new class introduced in Es6 version.  Other Classes are Set , WeakSet and WeakMap
The map is a data structure with key and value. Keys can be any arbitrary value and values can be an object or primitive types.
Keys can be a Primitive type like Strings, numbers, Symbols, Functions, Objects, and Dates. We can implement hashmap using the map in javascript and Typescript. It is ordered for insertion based.
Typescript has no built-in classes supported for Map, But Typescript supports same data structure that ES6 supports.

Es6 classes can be used in typescript with configuring Es6 library in typescript configuration.
In the tsconfig.json file, add "lib": ["es6"] or you can add polyfill.js for this classes.
This example mentioned will work in Typescript and Javascript.
let/var map=new Map()
let/var  map=new Map([iterablecollection])


var map = new Map()
map.set(new Date(), function currentTime () {})
map.set(() => 'key', { objectkey: 'objectvalue' })
map.set(Symbol('symbol'), [6, 21])
output is
0:{Fri Aug 31 2018 11:10:15 GMT+0530 (India Standard Time) => function currentTime() {}}
1:{key:() => 'key' value:{objectkey: "objectvalue"}}
2:{key:Symbol(symbol) value:(2) [6, 21]}
Map object created with a passing object during object creation. Object should contains iterable collection which outputs -[['key', 'value'], ['key', 'value']].
var map = new Map([
  ["key1", "value1"],
  ["key2", "value2"]])
  console.log(map) //{"key1" => "value1", "key2" => "value2"}

Adding elements to Map using set method

Map object can be created and add elements using Set() method
var map = new Map()
map.set('k', 'v')
map.set('k1', 'v1')
console.log(map) //{"k" => "v", "k1" => "v1"}


 Let us create Map using new Operator.
let map=new Map()
Method Description Example
Set(key,value) Adding key and value to Map
map.set("key1", "value");
map.set("key2", "value2");
console.log(map.size) // 2
get(key) Get element for the give key. returns Undefiend, if key not exists.
console.log(map.get("key1")) // value1
has(key) return true - if key exists in Map, else false.
console.log(map.has("key1")) // true
console.log(map.has("key45")) // false
delete(key) Delete key and value for given key from Map
console.log(map) // {"key1" => "value1", "key2" => "value2"}
console.log(map.delete("key1")) // returns true if deleted
console.log(map.delete("key1231")) // returns false if key doest not exist
console.log(map) //{"key2" => "value2"}
clear() Remove all key and values of a Map
console.log(map) // {"key1" => "value1", "key2" => "value2"}
map.clear()// returns nothing
console.log(map) //{}
size Return size of Map
console.log(map) // {"key1" => "value1", "key2" => "value2"}
console.log(map.size) //2
keys() Return keys with iterable collection of Map
for (let key of map.keys()) {
    console.log(key);                   //key1 key2
values() Return values with iterable collection of Map
for (let value of map.values()) {
    console.log(value);                   //value value2
entries() Return keys and values with iterable collection of Map
//map entries iteration
for (let entry of map.entries()) {
    console.log(entry[0], entry[1]);    //key1 value  key2 value2
forEach(calback,args) This is other way of doing iteration. Each element is applied with function exectuion.
      console.log(key, value);   //key1 value  key2 value2

Map Usage Example

let map = new Map();
map.set("kiran", "35");
map.set("john", "50");
map.set("tom", "45");
//map size returns
//map has
//map keys Iteration
for (let key of map.keys()) {
console.log(key);                   //kiran john tom
//map values iteration
for (let value of map.values()) {
console.log(value);                 //35 50 45
//map entries iteration
for (let entry of map.entries()) {
console.log(entry[0], entry[1]);    //kiran 35 john 50 tom 45
//object destructuring
for (let [key, value] of map) {
console.log(key, value);   //kiran 35 john 50 tom 45        
//Map forEach Iteration
console.log(key, value); //kiran 35 john 50 tom 45
 Map SameValueZero Example
Keys in Map checked using using SameValueZero algorithm.
SameValueZero is like === operator check with few diferences

NaN is not equal to NAN
+0 is equal to -0

const map = new Map()
map.set(NaN, 'testvalue')
console.log(map.get(NaN)) // 'testvalue
map.set(-0, 54);
console.log(map.get(+0)) // 54
console.log(NaN === NaN) // false
console.log(+0 === -0) // true

Related article