Memoization caches a function's results by its inputs, so repeated calls with the same arguments skip the work. memoize(fn) creates a Map and returns a wrapper that closes over it: if cache.has(arg), return cache.get(arg); otherwise call fn, store the result, and return it. Each memoized function gets its own private cache.
Three details interviewers check: use has, not a truthiness test, so cached 0, '' or undefined count as hits; forward this with call; and use a Map, not an object, so keys aren't converted to strings (1 and '1' stay distinct).
The hard part is the key:
- One primitive argument.
Mapcompares with SameValueZero, soNaNfindsNaN. ButMapalso canonicalises-0to+0, so a function that distinguishes them returns the wrong cached value. - Several arguments.
JSON.stringify(args)is the common shortcut and it's lossy:undefined,NaNand functions all becomenull, aMapbecomes{}, aDatebecomes the same string as its ISO text, BigInt throws, and two equal objects with different key order give different keys.args.join(',')makes(1, 2)and('1,2')collide. A collision-free option is a nestedMapper argument position. - Object arguments. Keying by identity is fast but misses mutation: change the object and you get a stale result. Keying by structure costs a deep serialisation per call. Pick deliberately; immutable data makes identity keys correct.
Two rules sit around all of this. Only memoize pure functions — anything reading time, randomness or mutable state returns stale data. And bound the cache: an unbounded Map grows forever, so use an LRU, a TTL, or a WeakMap when keys are objects.