-
Notifications
You must be signed in to change notification settings - Fork 2
/
weak-valued-map.ts
111 lines (85 loc) · 1.98 KB
/
weak-valued-map.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// A weakly valued map that automatically removes entries when they are garbage
// collected.
export class WeakValueMap<K, V extends object> {
#map = new Map<K, WeakRef<V>>()
#registry = new FinalizationRegistry<K>((heldValue) => {
this.#map.delete(heldValue)
})
clear(): void {
for (const [, ref] of this.#map) {
const value = ref.deref()
if (value) {
this.#registry.unregister(value)
}
}
this.#map.clear()
}
delete(key: K): boolean {
const ref = this.#map.get(key)
if (!ref) {
return false
}
this.#map.delete(key)
const value = ref.deref()
if (value) {
this.#registry.unregister(value)
}
return true
}
*entries(): IterableIterator<[K, V]> {
for (const [key, ref] of this.#map.entries()) {
const value = ref.deref()
if (value) {
yield [key, value]
}
}
}
forEach(
callbackfn: (value: V, key: K, map: WeakValueMap<K, V>) => void,
thisArg?: any,
): void {
for (const [key, ref] of this.#map.entries()) {
const value = ref.deref()
if (value) {
callbackfn.call(thisArg, value, key, this)
}
}
}
get(key: K): V | undefined {
return this.#map.get(key)?.deref()
}
has(key: K): boolean {
return this.#map.get(key)?.deref() !== void 0
}
*keys(): IterableIterator<K> {
for (const [key, ref] of this.#map.entries()) {
const value = ref.deref()
if (value) {
yield key
}
}
}
set(key: K, value: V): this {
this.#map.set(key, new WeakRef(value))
this.#registry.register(value, key, value)
return this
}
get size() {
let size = 0
for (const [, ref] of this.#map.entries()) {
const value = ref.deref()
if (value) {
size++
}
}
return size
}
*values(): IterableIterator<V> {
for (const [, ref] of this.#map.entries()) {
const value = ref.deref()
if (value) {
yield value
}
}
}
}