Skip to content

Instantly share code, notes, and snippets.

@TylorS

TylorS/WeakRefMap.ts

Created May 27, 2021
Embed
What would you like to do?
WeakRefMap
export class WeakRefMap<K, V extends object> {
#weakRefs = new Map<K, WeakRef<V>>()
#registry = new FinalizationRegistry((key) => this.#weakRefs.delete(key))
has = (key: K) => this.#weakRefs.has(key)
get = (key: K) => this.#weakRefs.get(key)?.deref()
set = (key: K, value: V) => {
const ref = new WeakRef(value)
this.#weakRefs.delete(key)
this.#registry.register(value, key, ref)
this.#weakRefs.set(key, ref)
return this
}
delete = (key: K) => {
const ref = this.#weakRefs.get(key)
if (ref) {
this.#registry.unregister(ref)
}
return this.#weakRefs.delete(key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment