-
Notifications
You must be signed in to change notification settings - Fork 2
/
enumerable-weak-set.ts
124 lines (94 loc) · 2.15 KB
/
enumerable-weak-set.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
112
113
114
115
116
117
118
119
120
121
122
123
124
// An enumerable WeakSet created using WeakRefs.
export class WeakSet<T extends object> implements Set<T> {
#set = new Set<WeakRef<T>>()
#registry = new FinalizationRegistry<WeakRef<T>>((heldValue) => {
this.#set.delete(heldValue)
})
#find(value: T): WeakRef<T> | undefined {
for (const ref of this.#set) {
if (ref.deref() === value) {
return ref
}
}
}
add(value: T): this {
if (this.has(value)) {
return this
}
const ref = new WeakRef(value)
this.#set.add(ref)
this.#registry.register(value, ref, ref)
return this
}
clear(): void {
this.#set.forEach((ref) => {
this.#registry.unregister(ref)
})
this.#set.clear()
}
delete(value: T): boolean {
const ref = this.#find(value)
if (ref === void 0) {
return false
}
this.#registry.unregister(ref)
this.#set.delete(ref)
return true
}
forEach(
callbackfn: (value: T, value2: T, set: WeakSet<T>) => void,
thisArg?: any,
): void {
for (const ref of this.#set) {
const value = ref.deref()
if (value !== void 0) {
callbackfn.call(thisArg, value, value, this)
}
}
}
has(value: T): boolean {
return this.#find(value) !== undefined
}
get size(): number {
let size = 0
for (const ref of this.#set) {
if (ref.deref() !== undefined) {
size++
}
}
return size
}
*entries(): IterableIterator<[T, T]> {
for (const ref of this.#set) {
const value = ref.deref()
if (value !== undefined) {
yield [value, value]
}
}
}
*keys(): IterableIterator<T> {
for (const ref of this.#set) {
const value = ref.deref()
if (value !== undefined) {
yield value
}
}
}
*values(): IterableIterator<T> {
for (const ref of this.#set) {
const value = ref.deref()
if (value !== undefined) {
yield value
}
}
}
*[Symbol.iterator](): IterableIterator<T> {
for (const ref of this.#set) {
const value = ref.deref()
if (value !== undefined) {
yield value
}
}
}
[Symbol.toStringTag] = "Set"
}