Created
November 18, 2023 19:53
-
-
Save dy/a2fc54c476d09881aee36cb46eccd363 to your computer and use it in GitHub Desktop.
WeakishMap
This file contains hidden or 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
// 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