Full answer
A memoized function keeps a cache in a closure. On each call, it builds a key from the arguments. If the key is in the cache, it returns the stored value. Otherwise, it computes, stores, and returns the value. It trades memory for speed, and it fits expensive pure computations such as recursive Fibonacci, parsing, or price calculation.
Pitfalls to name:
- The function must be pure. If the result depends on time, randomness, or outside state, cached results become wrong.
- The key must be both unique and stable.
JSON.stringify(args)is a common choice, but it drops functions andundefined, treats objects with the same fields in a different order as different keys, and is slow for large inputs. For a single primitive argument, use the argument itself. For object arguments, aWeakMapkeyed by the object avoids leaks. - An unbounded cache is a memory leak with a good reputation. Set a maximum size or an expiry time.
- Return values that are objects are shared. A caller who mutates the cached object changes the result for everyone.
thismust be forwarded if the function is used as a method.
For a bounded cache, a Map iterates keys in insertion order. When the size passes the limit, delete the first key. For LRU, on every hit delete the key and set it again so it moves to the end.
For async functions, cache the promise, not the resolved value, so concurrent callers share one request. Remove the entry if the promise rejects, otherwise a temporary failure is cached forever.
function memoize(fn, { limit = Infinity, key = (...args) => JSON.stringify(args) } = {}) {
const cache = new Map();
const memoized = function (...args) {
const cacheKey = key(...args);
if (cache.has(cacheKey)) {
const value = cache.get(cacheKey);
cache.delete(cacheKey); // refresh position for LRU behavior
cache.set(cacheKey, value);
return value;
}
const value = fn.apply(this, args);
cache.set(cacheKey, value);
if (cache.size > limit) cache.delete(cache.keys().next().value);
return value;
};
memoized.cache = cache;
return memoized;
}
let computeCount = 0;
const slowSquare = memoize((n) => {
computeCount += 1;
return n * n;
}, { limit: 2 });
console.log(slowSquare(4), slowSquare(4), computeCount);
slowSquare(5);
slowSquare(4); // refreshes 4, so 5 is the oldest
slowSquare(6); // evicts 5
console.log([...slowSquare.cache.keys()]);
slowSquare(5);
console.log(computeCount);
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
console.log(fib(60));
function memoizeAsync(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
const promise = fn(arg).catch((error) => {
cache.delete(arg); // do not cache failures
throw error;
});
cache.set(arg, promise);
}
return cache.get(arg);
};
}
let requests = 0;
const loadUser = memoizeAsync(async (id) => {
requests += 1;
if (id === 0) throw new Error('not found');
return { id };
});
(async () => {
await Promise.all([loadUser(1), loadUser(1), loadUser(1)]);
console.log('requests for three concurrent calls:', requests);
await loadUser(0).catch(() => {});
await loadUser(0).catch(() => {});
console.log('requests after two failed calls:', requests);
})();Run with Node.js v24.22.1 as js-43.js; two runs gave identical output. Output: 16 16 1 [ '[4]', '[6]' ] 4 1548008755920 requests for three concurrent calls: 1 requests after two failed calls: 3
Key points
- Memoization caches results by argument key inside a closure.
- Only pure functions are safe to memoize.
- Choose stable keys; JSON.stringify has limits.
- Bound the cache by size or time; Map insertion order gives a simple LRU.
- For async work, cache the promise and drop it on rejection.
Common mistakes
- Memoizing impure functions such as ones that read the current time.
- Using JSON.stringify keys with object arguments where key order or functions matter.
- Leaving the cache unbounded in a long-running process.
- Caching a rejected promise, which makes a temporary error permanent.
Follow-ups
- How would you memoize a method that depends on this?
- How would you add a time-to-live to each cache entry?
- When is memoization the wrong tool, and what would you use instead?
Tips
- State the purity requirement first. It is the first thing a reviewer will check.
- Mention cache size limits without being asked; it separates a toy from a production answer.
- For async functions, say "cache the promise" and explain the concurrency benefit.