Created
May 27, 2021 14:48
-
-
Save TylorS/a47a1a2e926831294248e97c31af77c1 to your computer and use it in GitHub Desktop.
WeakRefMap
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 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