🟑 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