Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Memoize with a custom cache key in JavaScript

105 Memoisation, and why the cache key is the hard part

hard

Write a memoiser that takes the key function as an argument, then break it four ways with the key rather than the recursion: a joined key that two different argument lists share, JSON.stringify flattening undefined and null into the same thing, two equal objects whose keys are in a different order, and keying on the object itself. Count hits and misses so every claim is measurable.

Stuck? Three hints, smallest first
  1. 1. The cache is a Map from key to result. The only interesting decision is how the key is made.
  2. 2. args.join(',') cannot tell ['a,b'] from ['a', 'b'].
  3. 3. JSON.stringify writes undefined, null and NaN in an array all as null.

The answer

function memoise(fn, keyOf) {
  const cache = new Map();
  const wrapped = (...args) => {
    const key = keyOf(...args);
    if (cache.has(key)) {
      wrapped.hits += 1;
      return cache.get(key);
    }
    wrapped.misses += 1;
    const value = fn(...args);
    cache.set(key, value);
    return value;
  };
  wrapped.hits = 0;
  wrapped.misses = 0;
  wrapped.keys = () => [...cache.keys()];
  return wrapped;
}

const joinKey = (...args) => args.join(',');
const jsonKey = (...args) => JSON.stringify(args);
const stableKey = (...args) =>
  JSON.stringify(args, (key, value) =>
    value && typeof value === 'object' && !Array.isArray(value)
      ? Object.fromEntries(Object.entries(value).sort((a, b) => (a[0] < b[0] ? -1 : 1)))
      : value);

// 1. A joined key cannot tell one comma-containing argument from two arguments.
let placeRuns = 0;
const place = (...parts) => { placeRuns += 1; return parts.filter(Boolean).join(' / '); };
const byJoin = memoise(place, joinKey);
const joinedCollision = [byJoin('Lagos,Ikeja'), byJoin('Lagos', 'Ikeja'), byJoin.hits, placeRuns];

const byJson = memoise(place, jsonKey);
const jsonKeepsThemApart = [byJson('Lagos,Ikeja'), byJson('Lagos', 'Ikeja'), byJson.misses];

// 2. JSON.stringify writes undefined, null and NaN in an array identically.
let kindRuns = 0;
const kindOf = (value) => { kindRuns += 1; return value === null ? 'null' : typeof value; };
const kind = memoise(kindOf, jsonKey);
const forUndefined = kind(undefined);
const forNull = kind(null);
const forNaN = kind(Number.NaN);
const threeWayCollision = [forUndefined, forNull, forNaN, kind.keys(), kindRuns];

// 3. Key order changes the JSON, so the same box is measured twice.
let areaRuns = 0;
const area = (box) => { areaRuns += 1; return box.w * box.h; };
const byOrder = memoise(area, jsonKey);
const orderMatters = [byOrder({ w: 2, h: 3 }), byOrder({ h: 3, w: 2 }), byOrder.misses];

const bySorted = memoise(area, stableKey);
const sortedFixesIt = [bySorted({ w: 2, h: 3 }), bySorted({ h: 3, w: 2 }), bySorted.misses, bySorted.hits];

// 4. Keying on the object itself is identity, not equality.
const byIdentity = memoise(area, (box) => box);
const shared = { w: 4, h: 5 };
const identity = [byIdentity(shared), byIdentity(shared), byIdentity({ w: 4, h: 5 }), byIdentity.hits, byIdentity.misses];

const totalRuns = areaRuns;
const cacheGrowth = [byOrder.keys().length, bySorted.keys().length, byIdentity.keys().length];

console.log('joined key :', joinedCollision);
console.log('json key   :', jsonKeepsThemApart);
console.log('undefined, null, NaN share the key', kind.keys());
console.log('identity   :', identity);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a joined key collides, and the second call is served the first answer as a hit', joinedCollision, ['Lagos,Ikeja', 'Lagos,Ikeja', 1, 1]);
test('a JSON key keeps the two argument lists apart, so both answers are right', jsonKeepsThemApart, ['Lagos,Ikeja', 'Lagos / Ikeja', 2]);
test('undefined, null and NaN all stringify to null, so one key serves all three wrongly', threeWayCollision, ['undefined', 'undefined', 'undefined', ['[null]'], 1]);
test('two identical boxes written in a different key order miss each other', orderMatters, [6, 6, 2]);
test('sorting the keys before stringifying fixes it: one miss, one hit', sortedFixesIt, [6, 6, 1, 1]);
test('keying on the object gives identity: the same object hits, an equal one does not', identity, [20, 20, 20, 1, 2]);
test('the underlying function ran exactly once per miss, never once per call', [totalRuns, byOrder.misses + bySorted.misses + byIdentity.misses], [5, 5]);
test('and nothing is ever evicted: every distinct key is still in the map', cacheGrowth, [2, 1, 2]);

Memoisation also appears in the Recursion section, where the subject is the recursion — the same subproblem being solved thousands of times. Here the recursion is beside the point and the key is the whole exercise, because that is where the bugs are. A memoiser with a wrong key does not run slowly, it returns the wrong answer, which is a far worse failure than the one it was added to fix.

The first three assertions are the same mistake at three depths. args.join(',') flattens structure away, so one argument containing a comma and two arguments look identical. JSON.stringify keeps the structure but flattens three distinct values — undefined, null and NaN — into null, so a function that behaves differently for each gets one cached answer for all three. And key order in an object is part of the JSON, so two objects that are equal in every way that matters produce two entries and two runs. Sorting the keys fixes the last one; the other two need the key function to know something about the arguments.

The sixth assertion is a different tool rather than a worse one. Keying on the object itself is identity comparison, which is wrong when callers build a fresh options object per call and exactly right when the argument is a long-lived entity — a DOM node, a request, a record. That is the case a WeakMap is for, and it brings the one property a Map of stringified keys can never have: the entry disappears when the key object is collected. Which brings the last assertion: A Map-based memoiser is an unbounded cache with no invalidation, and the eighth assertion is that stated plainly — the keys are all still there. That is fine for a pure function over a small domain, and a memory leak for anything keyed on user input. Add a maximum size with LRU eviction, or a TTL as in exercise 90, before this goes anywhere near a long-running process. Also note what memoisation assumes: that fn is pure. Memoise something that reads a clock, a database or a random number and you have cached its first answer for ever.

Newsletter

New writing, when it lands.

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