MCPcopy Create free account
hub / github.com/WebReflection/weak-value / WeakValue

Class WeakValue

esm/index.js:12–90  ·  view source on GitHub ↗

* A Map extend that transparently uses WeakRef around its values, * providing a way to observe their collection at distance. * @extends {Map}

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 3

onValueCollectedFunction · 0.85
deleteMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected