JS Built-ins
FunctionalProgrammingbeginner

Basic memoization β€” cache results

πŸ“– Usage Example
function memoize(fn) {
  const cache = {};
  return function(x) {
    if (x in cache) return cache[x];
    return (cache[x] = fn(x));
  };
}
const memoSqrt = memoize(Math.sqrt);
memoSqrt(25); // 5 (computed)
memoSqrt(25); // 5 (cached)

Memoization caches the result of a function call to avoid redundant computation.

Memoization Fundamentals

Memoization caches function results to avoid recomputation. This is useful for expensive operations.

Challenge: Implement a memoize function that caches results for single-argument functions. Repeated calls with the same argument should return cached results.

πŸ’‘ Hints (3)
  • β€’ Create a cache object inside memoize
  • β€’ Check if value exists in cache
  • β€’ If not, compute and store result