MediumFunctions📖 Theory Question

What is memoization and how do you implement it?

💡

Hint

Cache results keyed by arguments — avoid recomputing for the same inputs

Full Answer

Memoization is an optimization where a function caches its results. Calling with the same inputs returns the cached result instead of recomputing.

function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key); // cache hit
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

// Fibonacci without memoization: O(2^n)
// With memoization: O(n)
const fib = memoize(function(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2); // self-referencing
});

fib(40); // instant — 40 cache entries
fib(40); // instant again — cache hit

When to use: Pure functions with expensive computation and repeated same-argument calls. React's useMemo and useCallback implement this concept.

💡 Only memoize PURE functions — same input must always give same output. Don't memoize time-dependent or side-effectful functions.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint