Created
December 20, 2023 10:48
-
-
Save andremichelle/cd517f2afe297df938d241c07c243c3d to your computer and use it in GitHub Desktop.
WeakRefSet holds weak references and is iterable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class WeakRefSet<T extends WeakKey> { | |
readonly #set = new Set<WeakRef<T>>() | |
add(value: T): void {this.#set.add(new WeakRef<T>(value))} | |
forEach(callback: (value: T) => void): void { | |
for (const weakRef of this.#set) { | |
const value = weakRef.deref() | |
if (value === undefined) { | |
this.#set.delete(weakRef) | |
} else { | |
callback(value) | |
} | |
} | |
} | |
countReferences(): number { | |
let count = 0 | |
this.forEach(() => count++) | |
return count | |
} | |
clear(): void {this.#set.clear()} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment