๐ง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.
replit๏ผfactorial (memoization by 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
Was this helpful?