Skip to content

Instantly share code, notes, and snippets.

@dy
Created November 18, 2023 19:53
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 dy/a2fc54c476d09881aee36cb46eccd363 to your computer and use it in GitHub Desktop.
Save dy/a2fc54c476d09881aee36cb46eccd363 to your computer and use it in GitHub Desktop.
WeakishMap
// based on https://github.com/WebReflection/not-so-weak/
const refs = new WeakMap;
const set = value => {
const ref = new WeakRef(value);
refs.set(value, ref);
return ref;
};
const get = value => refs.get(value) || set(value);
export class WeakishMap extends Map {
#registry = new FinalizationRegistry(key => super.delete(key));
get size() { return [...this].length }
constructor(entries = []) {
super();
for (const [key, value] of entries) this.set(key, value);
}
get(key) {
return super.get(key)?.deref();
}
set(key, value) {
let ref = super.get(key);
if (ref) this.#registry.unregister(ref);
ref = get(value);
this.#registry.register(value, key, ref);
return super.set(key, ref);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment