๐Ÿงšmemoize by closure

make a function "remember" its return values by closure.

JS โŸฉ technique โŸฉ memoize โŸฉ by decorator

make a function "remember" its return values by using closure.

// โญ factorial wrapped in a closure (IIFE)
const factorial = (() => {

    // โญ internal cache for f
    const cache = {};

    return function f(x) {

        // base case:
        if (x < 2) return 1;
        // recursive case:
        if (!(x in cache)) cache[x] = x * f(x - 1);

        return cache[x];
    }

})();

factorial(6)    // 720
factorial(7)    // 5040

Last updated