Memoization Patterns for JavaScript Interviews
JS جاوااسکریپت

Memoization Patterns for JavaScript Interviews

Cache expensive pure function results with closures, Map, and LRU strategies.

BugCast Admin··۵ دقیقه مطالعه

Memoization trades memory for speed by caching inputs to outputs. It only works correctly for pure functions with stable argument comparison.

Common Interview Questions

Q: Implement basic memoize for single-argument functions

Answer: Map keys use SameValueZero equality. For multiple arguments, serialize with JSON or a custom key function — mind object key identity.


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

Q: When should you NOT memoize?

Answer: Impure functions, functions with side effects, rapidly changing inputs, or when memory cost exceeds compute savings. Also avoid unbounded caches in long-lived processes.

Q: How does React's useMemo relate?

Answer: useMemo memoizes a computed value between renders when dependencies are unchanged. It is a React optimization, not a general-purpose cache across calls outside the component.

Q: What is an LRU cache?

Answer: Least Recently Used eviction removes oldest entries when capacity is exceeded. Useful for bounded memoization in interview system design follow-ups.

Key Points for Interviews

  • Requires pure functions for correctness

  • Argument serialization is the hard part for multi-arg memoize

  • Fibonacci recursive demo is the classic teaching example

  • Bound cache size in production to prevent memory growth

  • Distinguish memoization from debouncing/throttling

#memoization#performance#interview

مطالب مرتبط