Start with one argument: a Map from argument to result, returning the cached value on a hit. Then follow the requirements as they change. Several arguments: a tree of Maps, one level per argument, rather than JSON.stringify(args), which mixes up 1 and '1', loses undefined, and gives two different objects the same key. Control: a custom key function, a clear(). Limits: an LRU size cap (a Map's insertion order doubles as recency) and a TTL. Async: cache the promise so concurrent calls share one request, but drop it on rejection. Throughout: don't cache thrown errors, and do cache undefined results (has, not a truthiness check).
Implement memoization, then extend the behavior as requirements change.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
cache.has(arg) rather than if (cache.get(arg)), so undefined, 0 and false results are cached too. Map keys use SameValueZero (like ===, except NaN matches itself), so objects are cached by identity. fn.call(this, arg) keeps memoized methods working.
// One argument: remember each result by its argument.function memoize(fn) {const cache = new Map(); // Map keys compare like ===, so objects are cached by identityreturn function (arg) {if (!cache.has(arg)) cache.set(arg, fn.call(this, arg));return cache.get(arg);};}
passes 3 checks run on every build, against the native method where there is one
- computes once per argument
- undefined and falsy results are cached too
- objects by identity
Walk a tree of Maps, one level per argument, and store the result under a symbol at the end. That keeps every argument's identity and type: no string keys to collide, so 1 and '1' differ and two equal-looking objects stay apart (the last check shows how JSON.stringify keys return the wrong object). A call that throws stores nothing, so the next call tries again.
// Any number of arguments: a tree of Maps, one level per argument. No string keys, so 1 and// '1' stay different and objects work by identity.const RESULT = Symbol('result');function memoize(fn) {let root = new Map();function memoized(...args) {let node = root;for (const arg of args) {if (!node.has(arg)) node.set(arg, new Map());node = node.get(arg);}// A thrown error isn't cached: the next call tries again.if (!node.has(RESULT)) node.set(RESULT, fn.apply(this, args));return node.get(RESULT);}memoized.clear = () => {root = new Map();};return memoized;}
passes 6 checks run on every build, against the native method where there is one
- several arguments
- 1 and '1' are different; NaN matches NaN
- different numbers of arguments are different calls
- errors aren't cached
- clear forgets everything
- why not JSON.stringify(args): objects with the same JSON aren't the same object
A key function lets callers choose what counts as the same call (lodash's resolver). A Map iterates in insertion order, so deleting and re-setting an entry on each hit makes the first key the least recently used, which is the one to evict past maxSize. Each entry stores when it expires. For async functions, cache the promise so concurrent calls share one request, and delete it if it rejects. Otherwise one failed request is returned forever.
// Requirements that change in the interview: a key function, a size limit (least recently// used goes first), an expiry time, and async functions whose failures mustn't stick.function memoize(fn, { key = (first) => first, maxSize = Infinity, ttl = Infinity } = {}) {const cache = new Map(); // key -> { value, expires }; Map order doubles as recency orderfunction memoized(...args) {const k = key(...args);const hit = cache.get(k);if (hit && hit.expires > Date.now()) {cache.delete(k); // move to the end: most recently usedcache.set(k, hit);return hit.value;}cache.delete(k); // expired or missingconst value = fn.apply(this, args);const entry = { value, expires: Date.now() + ttl };cache.set(k, entry);if (cache.size > maxSize) cache.delete(cache.keys().next().value); // evict the oldest// Cache the promise itself, so concurrent calls share one request, but forget it if it// rejects, so one failure doesn't become a permanent cached failure.if (value && typeof value.then === 'function') {value.then(undefined, () => {if (cache.get(k) === entry) cache.delete(k);});}return value;}memoized.cache = cache;return memoized;}
passes 5 checks run on every build, against the native method where there is one
- a key function
- maxSize evicts the least recently used
- ttl expires entries
- concurrent async calls share one promise
- a rejected promise is forgotten, so the next call retries
React's memo hooks
useMemo, useCallback and React.memo keep only the last inputs (a cache of size one) and compare dependencies with Object.is.
Selector libraries
Reselect's createSelector memoizes derived state so components don't re-render when the inputs haven't changed; its default cache is also size one, with an LRU option.
Request deduplication
Data-fetching libraries share one in-flight request between components asking for the same key and don't keep failures, the same idea as the async part of the advanced stage.
if (cache.get(key))instead ofcache.has(key), which recomputes falsy results.JSON.stringify(args)as the key:1vs'1'collide,undefineddisappears, functions and cycles break, different objects share a key.An unbounded cache in a long-running page or server: a memory leak.
Memoizing impure functions (time, randomness, mutable inputs).
Caching a rejected promise forever.
How would you avoid leaking memory for object arguments?
Use a WeakMap at levels whose key is an object: when nothing else references the object, its cache entry can be collected. WeakMap can't hold primitives, so mix it with a Map.
What does lodash's memoize key on by default?
The first argument only, unless you pass a resolver. That surprises people who memoize two-argument functions.
Is memoization always a win?
No: for cheap functions, the hashing and memory cost more than recomputing. Measure first, and memoize functions that are pure and actually expensive.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
- lodash.com/docs/4.17.15#memoize
- react.dev/reference/react/useMemo