-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
87 lines (74 loc) · 1.61 KB
/
utils.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
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
function onlyStringAllowed (value) {
if (typeof value !== 'string') throw new Error('This environment does not support ES2015 Map/Set. Only string allowed!')
}
function FakeSet (arr) {
this.data = {}
this.size = 0
arr = arr || []
for (var i = 0, len = arr.length; i < len; i++) {
this.add(arr[i])
}
}
FakeSet.prototype.has = function (value) {
onlyStringAllowed(value)
return value in this.data
}
FakeSet.prototype.add = function (value) {
onlyStringAllowed(value)
this.size++
this.data[value] = true
}
FakeSet.prototype.delete = function (value) {
onlyStringAllowed(value)
this.size--
delete this.data[value]
}
function FakeMap () {
this.size = 0
this.data = {}
}
FakeMap.prototype.has = function (key) {
onlyStringAllowed(key)
return key in this.data
}
FakeMap.prototype.get = function (key) {
onlyStringAllowed(key)
return this.data[key]
}
FakeMap.prototype.set = function (key, value) {
onlyStringAllowed(key)
this.size++
this.data[key] = value
}
FakeMap.prototype.delete = function (key, value) {
onlyStringAllowed(key)
this.size--
delete this.data[key]
}
function getSet (items, forceLegacy) {
try {
if (forceLegacy) throw new Error('Use fakeSet')
return new Set(items)
} catch (e) {
return new FakeSet(items)
}
}
function getMap (forceLegacy) {
try {
if (forceLegacy) throw new Error('Use fakeMap')
return new Map()
} catch (e) {
return new FakeMap()
}
}
function setToArray (set) {
if (set instanceof FakeSet) {
return Object.keys(set.data)
}
return Array.from(set)
}
module.exports = {
getSet,
getMap,
setToArray
}