-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash-map.js
More file actions
89 lines (55 loc) · 1.57 KB
/
hash-map.js
File metadata and controls
89 lines (55 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const map = new Map([["someKey", "someValue"]]);
// adding values
map.set("foo", "bar");
map.set(10, "buzz");
const symbol = Symbol("key");
map.set(symbol, "value for a symbol as key");
map.set(Symbol.for("keyOne"), "value for a universal symbol as key");
const fn = (x) => x + 1;
map.set(fn, "addOne");
map.set("addOne", fn);
const obj = {};
map.set(obj, "value for some object as key");
// getting values
console.log(map.get(obj));
console.log(map.get(fn));
console.log(map.get(symbol));
console.log(map.get(Symbol.for("keyOne")));
// deleting from the hash map
map.delete(obj);
// check if a value exists
console.log(map.has(obj)); // false as it was just deleted
console.log(map.has(fn)); // true
// getting the keys from the hash map
const keys = map.keys();
// getting the values from the hash map
const values = map.values();
// getting both keys and values
const entries = map.entries();
// keys,values and entries return an iterator
console.log(keys.next());
for (const key of keys) {
console.log("key", key);
}
for (const value of values) {
console.log("value", value);
}
for (const [key, value] of entries) {
console.log(key, value, "key-value pair");
}
// iterating with forEach
// no idea why value comes first
map.forEach((value, key, map) => {
console.log(key, value);
});
// for of loop with map
for (const [key, value] of map) {
console.log(key, value);
}
/** MAP is not serializable to JSON */
console.log(JSON.stringify(map), "map stringified");
// get map size
console.log(map.size);
// clear the hash map
map.clear();
console.log(map.size); // 0