Thursday, September 6, 2018

Es6 Beginner guide to Weakmap class examples in javascript | Typescript WeakMap

WeakMap class in Javascript

Es6 introduced new collection data structure classes. WeakMap is one of the collection class similar to Map class, Other Classes are SetMap and WeakSet Other Classes are Set, Map and WeakSet

WeakMap is a map class which stores key and values and keys stores weak references,  that is if the reference of the key is unreferenced, value for the given key is garbage collected.

So weakMap saves weak references of a key object. if the key object is referenced/destroyed, Garbage collector automatically removes the entry(key and value ) from  WeakMap and memory consumption is less

Typescript WeakMap Example

Typescript has no support for Map or WeakMap, Typescript is an extended version of javascript/ES6, We can use with some configuration. 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. Typescript has no built-in classes supported for Map, But Typescript supports same data structure that ES6 supports.

WeakMap Declare and Creation

Empty WeakMap is created using the new keyword
new WeakMap() 
Can also create using iterable objects, these objects contain key and values pairs
new WeakMap(iterable : Object)
For example, We will create a Map using an array of key and values
var key = { id: 1 };
var value = { name: 'kiran' };
var map = new WeakMap([[key, value]]);
console.log(map)
Output is
[[Entries]]: Array(1)
0: {Object => Object}
key: {id: 1}
value: {name: "kiran"}
length: 1

Methods. 

WeakMap has only methods for adding/removing, check keys, empty map operations. iterable operations are not implemented.

WeakMap.set() method

It stores key and values in the map Syntax
set(key : Object, value : Object) : WeakMap
Primitive types - String, Boolean, Number, Undefined and Symbole Objects are not allowed for the key value. Only objects are allowed
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.has(key)) 
console.log(weakMap.has(null)) 
Output is
[[Entries]]: Array(1)
0: {Object => "v"}
key: {id: 1}
value: "v"
length: 1

WeakMap.has() method

has() method returns true if the key already exists, else false
has(key : Object) : Boolean
the parameter is object key
Example
Here is an example of has method usage.
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.has(key)) //true
console.log(weakMap.has(null))  // false

WeakMap.delete() method

This method is used to remove the key from a map and true if exists, else false.
Syntax
delete(key : Object) : Boolean
Example
here is an example of delete method usage
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.delete(key))  // true
console.log(weakMap.delete(null))  // false

Allowed and not allowed Keys Example 

keys of WeakMap not allowed primitive types and Symbole object and gives compilation error - Argument of type 'Symbol' is not assignable to a parameter of type 'object'.
var map = new WeakMap()
map.set(new Date(), function currentTime () {})  // acceptable
map.set(() => 'key', { objectkey: 'objectvalue' })// acceptable
map.set(1,123) // not acceptable, primitive not allowed as keys
map.set(Symbol('symbol'), [6, 21]) // not acceptable, Symbole not allowed as keys
console.log(map) 

WeakMap and Map Usage difference example

Following is an example of Map and WeakMap methods usage
var map=new Map();
var weakMap=new WeakMap();
var object1={'one':'two'};
var object2={'five':'six'};
map.set(object1,'kiran')
weakMap.set(object2,'kiran2')
console.log(map.get(object1)) // kiran
console.log(map.get(object2)) // undefined

var map=new Map();
var weakMap=new WeakMap();
var object1={'one':'two'};
var object2={'five':'six'};
map.set(object1,'frank');
weakMap.set(object2,'frank2');
console.log(map.get(object1)); // frank
console.log(weakMap.get(object2)); // frank2

Difference between Map and WeakMap

Both used to store key and values only
Map WeakMap
Map Keys are strong references Keys of WeakMap are weak referenced/td>
Memory Consumption is high Memory Consumption is less, the entry will be automatically garbage collected if any keys are unreferenced
Keys can be a Primitive type like Strings, numbers, Date, Symbols, Functions, Objects, and Dates Keys cannot be Primitive types and Symbol object, Other objects are allowed
Map has iterator implementation methods like keys(),values(), entries() and forEach() methods Weakmap not not implemented iterator, so keys and values are not iterable

Related article


EmoticonEmoticon