Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Memoize with WeakMap in JavaScript

108 a memo keyed by object identity, in a WeakMap

fair

Memoise a function of one object argument in a WeakMap, so the cache entry disappears when the object does. Show that identity is the key rather than contents, that a cached 0 is still a hit, that mutating the object leaves the memo stale, and that a WeakMap offers nothing to enumerate.

Stuck? Three hints, smallest first
  1. 1. Use cache.has(key) to decide, not the truthiness of cache.get(key), or every cached 0, '' or false is recomputed for ever.
  2. 2. A WeakMap key must be an object. set with a string throws; get and has with one just answer politely.
  3. 3. There is no size, no keys and no forEach on a WeakMap. That absence is the feature, not an omission.

The answer

const memoByObject = (fn) => {
  const cache = new WeakMap();
  return (subject) => {
    if (cache.has(subject)) return cache.get(subject);
    const value = fn(subject);
    cache.set(subject, value);
    return value;
  };
};

let computations = 0;
const totalOf = (invoice) => {
  computations++;
  return invoice.lines.reduce((sum, line) => sum + line.units * line.price, 0);
};
const cachedTotal = memoByObject(totalOf);

const invoice = { ref: 'INV-9', lines: [{ units: 2, price: 4500 }, { units: 1, price: 1800 }] };
const twin = { ref: 'INV-9', lines: [{ units: 2, price: 4500 }, { units: 1, price: 1800 }] };

const first = cachedTotal(invoice);
const again = cachedTotal(invoice);
const callsAfterRepeat = computations;
const forTwin = cachedTotal(twin);
const callsAfterTwin = computations;

invoice.lines[0].units = 5;                 // the object changed; the cache did not notice
const stale = cachedTotal(invoice);
const truth = totalOf(invoice);
const callsAfterMutation = computations;

const secondMemo = memoByObject(totalOf);
const recomputed = secondMemo(invoice);
const callsAfterSecondMemo = computations;

let zeroCalls = 0;
const emptyTotal = memoByObject((inv) => {
  zeroCalls++;
  return inv.lines.length;
});
const empty = { ref: 'INV-0', lines: [] };
const zeros = [emptyTotal(empty), emptyTotal(empty), zeroCalls];

const weak = new WeakMap();
let keyError = 'no error';
try { weak.set('INV-9', 1); } catch (e) { keyError = e.constructor.name; }
const primitiveLookup = weak.has('INV-9');
const surface = [typeof weak.size, typeof weak.keys, typeof weak.forEach];

const strong = new Map();
strong.set({ ref: 'INV-1' }, 'held for ever');
const strongHolds = [...strong.keys()].length;

const secrets = new WeakMap();
class Wallet {
  constructor(pin) { secrets.set(this, { pin }); }
  matches(guess) { return secrets.get(this).pin === guess; }
}
const wallet = new Wallet('1234');
const walletShape = [JSON.stringify(wallet), Object.keys(wallet).length, wallet.matches('1234'), wallet.matches('0000')];

console.log('cached   :', first, again, '| calls:', callsAfterRepeat);
console.log('twin     :', forTwin, '| calls:', callsAfterTwin);
console.log('stale    :', stale, 'but the truth is', truth);
console.log('weakmap  :', keyError, primitiveLookup, surface);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the same object twice is one computation', [first, again, callsAfterRepeat], [10800, 10800, 1]);
test('an identical-looking twin is a different key, so it computes again', [forTwin, callsAfterTwin], [10800, 2]);
test('mutating the object does not invalidate anything: the memo is now wrong', [stale, truth, callsAfterMutation], [10800, 24300, 3]);
test('a second memo over the same function has its own cache', [recomputed, callsAfterSecondMemo], [24300, 4]);
test('a cached 0 is a hit, because has decided and not truthiness', zeros, [0, 0, 1]);
test('a WeakMap key must be an object: set throws, has just says no', [keyError, primitiveLookup], ['TypeError', false]);
test('and there is no size, no keys and no forEach to enumerate it with', surface, ['undefined', 'undefined', 'undefined']);
test('a Map used the same way keeps its keys reachable, and alive, for ever', strongHolds, 1);
test('a WeakMap keyed on this is how private state was done before # fields', walletShape, ['{}', 0, true, false]);

Keying on the argument itself means no serialisation, no key collisions and no key-order bugs — all the failures a JSON.stringify cache key has. The price is that identity is the only thing it can compare: two objects with the same contents are two entries, so this only pays off when callers hand you the same object repeatedly, which is exactly what happens with a React prop, a config object or a parsed document.

The WeakMap part is about lifetime. Entries hold their keys weakly, so an invoice that goes out of scope takes its cache entry with it and the memo cannot leak. The Map assertion is the contrast: a Map holds its keys strongly, and because you can list them, the collector can never conclude that nobody is looking. Being unable to enumerate a WeakMap is not a missing feature; it is the thing that makes weakness observable-free and therefore safe.

Staleness is the failure mode to remember. The cache is keyed on identity, not on contents, so mutating the object leaves the old answer in place and the memo confidently returns a number that is now wrong. Only memoise pure functions of values you treat as immutable — and if the data does change in place, the cache key has to change with it, which means a version counter or a fresh object.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.