* A Map extend that transparently uses WeakRef around its values, * providing a way to observe their collection at distance. * @extends {Map}
| 11 | * @extends {Map} |
| 12 | */ |
| 13 | class WeakValue extends Map { |
| 14 | #delete = (key, ref) => { |
| 15 | super.delete(key); |
| 16 | this.#registry.unregister(ref); |
| 17 | }; |
| 18 | |
| 19 | #get = (key, [ref, onValueCollected]) => { |
| 20 | const value = ref.deref(); |
| 21 | if (!value) { |
| 22 | this.#delete(key, ref); |
| 23 | onValueCollected(key, this); |
| 24 | } |
| 25 | return value; |
| 26 | } |
| 27 | |
| 28 | #registry = new FinalizationRegistry(key => { |
| 29 | const pair = super.get(key); |
| 30 | if (pair) { |
| 31 | super.delete(key); |
| 32 | pair[1](key, this); |
| 33 | } |
| 34 | }); |
| 35 | |
| 36 | constructor(iterable) { |
| 37 | super(); |
| 38 | if (iterable) |
| 39 | for (const [key, value] of iterable) |
| 40 | this.set(key, value); |
| 41 | } |
| 42 | |
| 43 | clear() { |
| 44 | for (const [_, [ref]] of super[iterator]()) |
| 45 | this.#registry.unregister(ref); |
| 46 | super.clear(); |
| 47 | } |
| 48 | |
| 49 | delete(key) { |
| 50 | const pair = super.get(key); |
| 51 | return !!pair && !this.#delete(key, pair[0]); |
| 52 | } |
| 53 | |
| 54 | forEach(callback, context) { |
| 55 | for (const [key, value] of this) |
| 56 | callback.call(context, value, key, this); |
| 57 | } |
| 58 | |
| 59 | get(key) { |
| 60 | const pair = super.get(key); |
| 61 | return pair && this.#get(key, pair); |
| 62 | } |
| 63 | |
| 64 | has(key) { |
| 65 | return !!this.get(key); |
| 66 | } |
| 67 | |
| 68 | set(key, value, onValueCollected = noop) { |
| 69 | super.delete(key); |
| 70 | const ref = new WeakRef(value); |
nothing calls this directly
no test coverage detected