Hint
Cache results keyed by arguments β avoid recomputing for the same inputs
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.