JS
S
JavaScriptWeakMap is a special kind of Map but the difference is that a WeakMap doesn't prevent an object from being garbage collected even though this object is used as the key in the WeakMap. Map allows keys of any type in advantage to Objects. Map preserves the order of insertion. Based on: http://javascript.info/map-set
1// Object ========================
2// Remember all keys are strings or will be converted to strings
3
4// Array ========================
5
6// WeakMap ========================
7
8// Map ========================
9let john = { name: "John" };
10let map = new Map();
11map.set('1', 'str1'); // a string key
12map.set(1, 'num1'); // a numeric key
13map.set(true, 'bool1'); // a boolean key
14map.set(john, 123); // an object key *Using objects as keys is one of most notable and important Map features.
15
16// remember the regular Object? it would convert keys to string
17// Map keeps the type, so these two are different:
18alert( map.get(1) ); // 'num1'
19alert( map.get('1') ); // 'str1'
20alert( map.size ); // 3
21map.keys() – returns an iterable for keys,
22map.values() – returns an iterable for values,
23map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of.
24// iterate over keys (vegetables)
25for (let vegetable of recipeMap.keys()) {
26 alert(vegetable); // cucumber, tomatoes, onion
27}
28
29// iterate over values (amounts)
30for (let amount of recipeMap.values()) {
31 alert(amount); // 500, 350, 50
32}
33
34// iterate over [key, value] entries
35for (let entry of recipeMap) { // the same as of recipeMap.entries()
36 alert(entry); // cucumber,500 (and so on)
37}
38
39// runs the function for each (key, value) pair
40recipeMap.forEach( (value, key, map) => {
41 alert(`${key}: ${value}`); // cucumber: 500 etc
42});
43
44// Instantiating in bulk
45let map = new Map([
46 ['1', 'str1'],
47 [1, 'num1'],
48 [true, 'bool1']
49]);
50
51// Create a map from object
52let obj = {
53 name: "John",
54 age: 30
55};
56let map = new Map(Object.entries(obj));
57
58// Create from map
59let prices = Object.fromEntries([
60 ['banana', 1],
61 ['orange', 2],
62 ['meat', 4]
63]);
64// now prices = { banana: 1, orange: 2, meat: 4 }
65alert(prices.orange); // 2
66
67// Map to Object
68let map = new Map();
69map.set('banana', 1);
70map.set('orange', 2);
71map.set('meat', 4);
72let obj = Object.fromEntries(map.entries()); // make a plain object (*)
73// done!
74// obj = { banana: 1, orange: 2, meat: 4 }
75alert(obj.orange); // 2
76
77// Caveats - chaining: every map.set call returns the map itself, so we can “chain” the calls:
78map.set('1', 'str1')
79 .set(1, 'num1')
80 .set(true, 'bool1');
81
82
83Created on 10/25/2019