Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Memoize a function in JavaScript

64 memoise, and the key that collides

hard

Write memoise(fn) that caches on a JSON.stringify of the arguments, and prove it saves a call. Then find its two failures: values that stringify identically share a cache entry, and two objects with the same contents in a different key order get separate entries. Fix the single-argument case with a Map keyed by the argument itself.

Stuck? Three hints, smallest first
  1. 1. Cache in a Map and use cache.has(key), not a truthy check, so a cached undefined or 0 still counts as a hit.
  2. 2. JSON.stringify([undefined]), JSON.stringify([null]) and JSON.stringify([NaN]) are all "[null]".
  3. 3. For one argument, skip stringifying: a Map compares keys with SameValueZero, so NaN, null and undefined stay separate.

The answer

const memoise = (fn) => {
  const cache = new Map();
  const memo = (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const value = fn(...args);
    cache.set(key, value);
    return value;
  };
  memo.keys = () => [...cache.keys()];
  return memo;
};

const memoiseByArg = (fn) => {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const value = fn(arg);
    cache.set(arg, value);
    return value;
  };
};

let fareCalls = 0;
const slowFare = (km, area) => {
  fareCalls++;
  return km * (area === 'Lekki' ? 2500 : 1000);
};
const fare = memoise(slowFare);
const first = fare(10, 'Lekki');
const repeated = fare(10, 'Lekki');
const different = fare(10, 'Ikeja');
const fareCallsAfter = fareCalls;

let kindCalls = 0;
const kindOf = (value) => { kindCalls++; return typeof value; };
const memoKind = memoise(kindOf);
const forUndefined = memoKind(undefined);
const forNull = memoKind(null);               // a HIT on the same key
const forNaN = memoKind(NaN);                 // another one
const kindCallsAfter = kindCalls;
const cachedKeys = memoKind.keys();

let areaCalls = 0;
const areaOf = (o) => { areaCalls++; return `${o.lga}/${o.zone}`; };
const memoArea = memoise(areaOf);
const inOrder = memoArea({ lga: 'Eti-Osa', zone: 'B' });
const reversed = memoArea({ zone: 'B', lga: 'Eti-Osa' });
const areaCallsAfter = areaCalls;

let exactCalls = 0;
const exact = memoiseByArg((value) => { exactCalls++; return String(value); });
const nanTwice = [exact(NaN), exact(NaN)];
const callsAfterNaN = exactCalls;
const nullAndUndefined = [exact(undefined), exact(null)];
const callsAtTheEnd = exactCalls;

console.log('fare      :', first, repeated, different, '| calls:', fareCallsAfter);
console.log('collision :', [forUndefined, forNull, forNaN], '| calls:', kindCallsAfter, '| keys:', cachedKeys);
console.log('key order :', inOrder, reversed, '| calls:', areaCallsAfter);
console.log('by arg    :', nanTwice, nullAndUndefined, '| calls:', callsAtTheEnd);

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('a repeat call comes back from the cache', [first, repeated], [25000, 25000]);
test('so the wrapped function ran once per distinct argument list', [different, fareCallsAfter], [10000, 2]);
test('but undefined, null and NaN all stringify to null, so they collide', [forUndefined, forNull, forNaN], ['undefined', 'undefined', 'undefined']);
test('one call, one cache entry, and two wrong answers', [kindCallsAfter, cachedKeys], [1, ['[null]']]);
test('the other way round, one meaning in two key orders gets two entries', [inOrder, reversed, areaCallsAfter], ['Eti-Osa/B', 'Eti-Osa/B', 2]);
test('keying a Map by the argument itself is exact, so NaN hits', [nanTwice, callsAfterNaN], [['NaN', 'NaN'], 1]);
test('and undefined and null stay apart', nullAndUndefined, ['undefined', 'null']);
test('which came to one call per genuinely distinct argument', callsAtTheEnd, 3);
test('has, not a truthy test, is what makes a cached falsy value a hit', memoiseByArg(() => 0)(1), 0);

Memoising is a trade of memory for time, and it is only correct for a pure function: cache slowFare and you win, cache anything that reads the clock or a database and you have frozen a stale answer for ever. The cache here also never evicts, so a long-lived memo over many arguments is a leak with a friendly name.

The key function is where the real bugs live, and JSON.stringify fails in both directions at once. It collides: undefined, null and NaN all become null, so three different calls share one entry and two of them get the wrong answer with no error. It also misses: object key order changes the string, so the same information passed twice is cached twice, and a Map, Set, Date or function argument stringifies to something useless. For one argument, key the Map on the argument itself — exact, no serialisation, and object arguments compare by identity, which is honest. For several, build a nested Map or accept the trade knowingly.

The last assertion is the small one that bites in practice: writing if (cache[key]) return cache[key] means a cached 0, '', false, null or undefined is recomputed every single time, which is a memo that quietly does nothing for exactly the functions you would most want to cache.

Newsletter

New writing, when it lands.

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