Functional patterns · mid
memoize, once and caching functions
Memoization wraps a pure function with a cache keyed by its arguments so repeated calls return the stored result; the senior details are the key strategy (JSON vs nested Map or WeakMap), caching promises for async functions (and evicting rejections), and bounding the cache size.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- One argument: a Map from argument to result. Several arguments: a resolver function, JSON.stringify(args) (costly, key-order issues, can't handle functions or cycles), or a nested Map trie (WeakMap for object arguments).
- Only memoize pure functions. Decide whether to preserve this.
- Async memoize: cache the promise right away (so concurrent calls share one request), delete it on rejection, and expire entries with a TTL timestamp.
- An unbounded cache is a memory leak: add a maximum size (LRU) or use WeakMap keys.
- once(fn): a flag plus the cached result. Variants: before(n), onlyTwice (Dream11: odd calls return the first result, even calls the second).
- React: useMemo caches per component instance and only for the last dependencies; React.memo shallow-compares props; React Compiler memoizes automatically. None of these is a global memoize.
The red pen
Common traps: mistake → fix
Mistake: JSON.stringify({ a: 1, b: 2 }) equals JSON.stringify({ b: 2, a: 1 })
Fix: it doesn't; key order matters.
Mistake: Caching rejected promises forever
Fix: one failure poisons every later call.
Mistake: Memoizing impure functions (Date.now, random, fetch without TTL).
Easy to hard
Questions interviewers ask, easy to hard
- Implement memoize for one argument.
- Several arguments: what key strategies exist and what breaks?
- Memoize an async function. What do you cache, and what about errors?
- Bound the cache with LRU or a TTL.
- How is useMemo different from memoize?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.