Code Snippets
/

Memoize Higher-Order Function

Memoize Higher-Order Function

Memoization caches function results keyed by arguments so repeat calls return in O(1). This snippet covers the canonical single-arg memoize, a multi-arg version that handles object identity via a `Map` chain, and an LRU-bounded variant that prevents unbounded cache growth. Use it for pure functions whose work dwarfs the lookup cost (parsing, layout calc, recursive DP).

JavaScript
Medium
3 snippets
utility
code-template
memoization
higher-order-functions

458 views

7

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

let calls = 0;
const fib = memoize((n) => {
    calls += 1;
    return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(20));         // 6765
console.log('calls:', calls); // 21 (each n computed once via the wrapper)
console.log(fib(20));         // 6765 (cache hit, no extra work)
console.log('calls:', calls); // 21

When the function takes one primitive argument (number, string, boolean), a plain Map is the cleanest cache: O(1) lookup, structural equality on keys, and no JSON.stringify overhead. Memoizing a recursive function flips a naive O(2^n) Fibonacci to O(n) by sharing sub-results, which is why DP problems get a speed-up just by adding this wrapper. The body must recurse through fib (the memoized binding) rather than a self-referencing inner name, otherwise the recursion bypasses the cache. Use this version any time the input space is small and primitive.