HybridWeakMap

trait~ HybridWeakMap

Drop-in replacement for WeakMap that can store primitives.

Note that primitive keys won't be weakly referenced (they cannot be garbage collected).

Like the original WeakMap, the elements of a HybridWeakMap cannot be iterated over.

const assert = require('assert');
const { strictEqual: assertIs } = require('assert');
const { HybridWeakMap } = require('ferrum');

let data = { obj: {}, prim: 'foo' }

const m = new HybridWeakMap([
  [data.prim,  42], // Primitive key, will be strongly referenced
  [data.obj,   23], // Object key, will be weakly referenced
]);

// Can retrieve the values
assertIs(m.get(data.prim), 42);
assertIs(m.get(data.obj),  23);
assert(m.has(data.prim));
assert(m.has(data.obj));

// Won't prevent object keys from being garbage collected.
// This is especially important for large key/value pairs:
// In this example our key and value are very small (empty object and a string),
// but if they where large, allowing them to be freed could release
// significant amounts of memory.

data = null; // Allow the {}/23 pair to be garbage collected.

Normally WeakMaps cannot store primitive values like Strings or Numbers; this is mostly an implementation detail and there still are some use cases where one would wish to store primitives in a weak map even though those primitive values won't be garbage collected.a

This is what HybridWeakMap is for: It simply contains two maps; one Weak map for objects, and one normal Map for primitives...