Skip to content

Instantly share code, notes, and snippets.

@TylorS
Created May 27, 2021 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylorS/a47a1a2e926831294248e97c31af77c1 to your computer and use it in GitHub Desktop.
Save TylorS/a47a1a2e926831294248e97c31af77c1 to your computer and use it in GitHub Desktop.
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