Skip to content

Instantly share code, notes, and snippets.

@andremichelle
Created December 20, 2023 10:48
Show Gist options
  • Save andremichelle/cd517f2afe297df938d241c07c243c3d to your computer and use it in GitHub Desktop.
Save andremichelle/cd517f2afe297df938d241c07c243c3d to your computer and use it in GitHub Desktop.
WeakRefSet holds weak references and is iterable
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