Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created April 18, 2020 07:55
Show Gist options
  • Save WebReflection/ff529d8033bcfd35b19dca0cdcfdf3d0 to your computer and use it in GitHub Desktop.
Save WebReflection/ff529d8033bcfd35b19dca0cdcfdf3d0 to your computer and use it in GitHub Desktop.
class WeakValue extends Map {
#registry = new FinalizationRegistry(key => {
if (this.has(key) && !this.get(key).deref())
this.delete(key);
});
get(key) {
const value = super.get(key);
return value && value.deref();
}
set(key, value) {
this.#registry.register(value, key);
return super.set(key, new WeakRef(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment