forked from handsontable/handsontable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiMap.js
52 lines (43 loc) · 1.15 KB
/
multiMap.js
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
export {MultiMap};
// TODO: Global expose for tests
window.MultiMap = MultiMap;
function MultiMap() {
var map = {
arrayMap: [],
weakMap: new WeakMap(),
};
return {
get: function(key) {
if (canBeAnArrayMapKey(key)) {
return map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
return map.weakMap.get(key);
}
},
set: function(key, value) {
if (canBeAnArrayMapKey(key)) {
map.arrayMap[key] = value;
} else if (canBeAWeakMapKey(key)) {
map.weakMap.set(key, value);
} else {
throw new Error('Invalid key type');
}
},
delete: function(key) {
if (canBeAnArrayMapKey(key)) {
delete map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
map.weakMap.delete(key);
}
},
};
function canBeAnArrayMapKey(obj) {
return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number');
}
function canBeAWeakMapKey(obj) {
return obj !== null && (typeof obj == 'object' || typeof obj == 'function');
}
function isNaNSymbol(obj) {
return obj !== obj; // NaN === NaN is always false
}
}