-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathstored-set.js
63 lines (53 loc) · 1.09 KB
/
stored-set.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
export default class StoredSet {
constructor(key, iterable) {
this._set = new Set(iterable)
this.key = key
this.reload()
window.addEventListener('storage', evt => {
if (evt.key === this.key) {
this.reload()
}
})
}
reload() {
const array = JSON.parse(window.localStorage.getItem(this.key)) || []
this._set.clear()
for (const val of array) {
this._set.add(val)
}
}
write() {
const array = Array.from(this._set.values())
window.localStorage.setItem(this.key, JSON.stringify(array))
}
add(value) {
const ret = this._set.add(value)
this.write()
return ret
}
clear() {
const ret = this._set.clear()
this.write()
return ret
}
delete(value) {
const ret = this._set.delete(value)
this.write()
return ret
}
entries() {
return this._set.entries()
}
forEach(callbackFn, thisArg) {
return this._set.forEach(callbackFn, thisArg)
}
has(value) {
return this._set.has(value)
}
keys() {
return this._set.keys()
}
values() {
return this._set.values()
}
}