Data structures in computer science refers to the programming storage of data for efficient usage in applications and algorithms. In the major release of javascript(ES6), four data structures were made available to the developers which really made javascript development further ease.
They are Map, WeakMap, Set and WeakSet.
Maps and WeakMaps
Maps are nothing but key-value pairs like objects but can contain only distinct keys. We can have primitive values or objects(may be functions etc…) as keys/values which differentiates the Maps from Objects.
The use case for maps and weakmaps are same with a major difference that weakmap is easily garbage collected, i.e they are removed from the memory when their purpose is served completely.
WeakMaps are adviced to use inside a method or a closure where its scope is properly defined.
WeakMap keys are weakly held and are objects, which also makes it difficult to get the overview of the weakMap. Lastly contents of the WeakMaps cannot be cleared.
Maps can be Initialized in two ways
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //Hash Maps creation in javascript //Simple way would be to call Map constructor and use the set method dynamically //whenever we need to add a new key-value pair to the map. let firstMap = new Map(); firstMap.set("key1","value1"); firstMap.set("key2","value2"); //Second way is to create a Map with default data while calling the constructor let secondMap = new Map([ ["key1","value1"], ["key2","value2"] ]); //this method expects array of arrays where the second level array should be //of length two. The first element is key and the second is value. |
Methods Supported
Map.set(key,value)
This method creates a new entry if the key doesn’t exist otherwise updates the value for the existing key.
Map.get(key)
This method returns the value for the key passed if the key exists otherwise returns undefined.
Map.has(key)
This method is used to verify if a key is present in the Map or not, returns a Boolean.
Map.delete(key)
This method is used to delete a key-value pair from the Map and returns a Boolean.
Map.clear()
This method removes all key-value pairs from the Map.
Methods used to iterate over Map elements
Map.keys()
This method returns an iterator which contains the keys present in the Map in the insertion order.
Map.values()
This method returns an iterator which contains the values present in the Map in the insertion order.
Map.entries()
This method returns an iterator of Arrays where the inner arrays contains the Key and Value as first and second element of the array.
Helper to Looping Maps
Map.forEach(function(value, key, map){})
This method calls the callback for each element in the insertion order with the provided arguments, the arguments are optional.
Properties
Map.size
This returns the number of key-value pairs present in the Map object.
Now lets see an example to familiarize ourselves with maps in javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //Counting the presence of a character in a word. //Lets see how Maps reduced the amount of code we had to write to achieve this let word = 'abcdabcdabcd'; let letters = new Map();//declaring Map for(let i=0;i<word.length;i++) { let letter = word[i]; if(letters.has(letter)) { letters.set(letter,letters.get(letter) + 1); } else { letters.set(letter,1); } } console.log(letters); //Output //"a"=>4,"b"=>4,"c"=>4,"d"=>4 |
Sets and WeakSets
Sets in javascript lets us store unique primitive values or objects in Array format.
Similar to WeakMaps, a WeakSet is a Set that doesn’t prevent its elements from being garbage-collected.
Sets can also be declared and added data or a Set can be initialized with default values.
1 2 3 4 5 6 7 8 9 10 11 12 | //Sets implementation //Initializing a set and adding data dynamically let firstSet = new Set(); firstSet.add(1); firstSet.add(2); //Adding some default data during initializing it to a variable let secondSet = new Set([1,2,3,4]); //Remember, even if we initialize it with an array containing //duplicate elements, the Set formed will contain only unique elements by //ignoring the duplicate ones. |
Methods Supported
Set.add(value)
This method adds a value to a Set, ignores if the value is already present in the Set.
Set.delete(value)
This method deletes the specified value from the Set if it exists, returns a Boolean.
Set.has(value)
This method verifies if the specified value is present in the Set, returns a Boolean.
Set.clear()
This method is used to clear the values present in the Set and make it an empty Set.
Methods used to iterate over Set elements
Set.values()
This method returns an iterator of elements in the order of insertion.
Set.keys()
This will do the exact same job as values() method.
Set.entries()
This method returns an iterator which contains Arrays as elements for each individual elements in Set. The Arrays are of length two where both the elements contain the value.
Helper to Looping Sets
Set.forEach(function(value, key, collection){})
This method calls the callback for each of the element present in the insertion order with the provided arguments, All of the arguments are optional. Here value and key both refer to the element.
Properties
Set.size
This returns the number of elements present in the Set.
Lets see an example to familiarize ourselves with Set in javascript.
1 2 3 4 5 6 7 8 9 | //Verifying if a letter present in a word const Verfy = (word,letter) => { let letters = word.split(''); let letter_set = new Set(letters); return letter_set.has(letter); } let trueCase = Verify("India","a");//return true; let falseCase = Verify("Goa","I");// returns false; |
Why do Maps and Sets have the property size and not length?
The reason for this difference is that length is for sequences, data structures that are indexable – like Arrays. size is for collections that are primarily unordered – like Maps and Sets.