const cache = {};
function memoize(fn) {
return function(...args) {
const key = JSON.stringify(args);
if (key in cache) return cache[key];
cache[key] = fn(...args);
return cache[key];
};
}
const double = memoize(x => x * 2);
const triple = memoize(x => x * 3);
double(5);
console.log(triple(5));function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (key in cache) return cache[key];
cache[key] = fn(...args);
return cache[key];
};
}
const double = memoize(x => x * 2);
const triple = memoize(x => x * 3);
double(5);
console.log(triple(5));Bug: cache is declared outside memoize — all memoized functions share one global cache. double(5)=10 is stored under key "[5]". triple(5) finds "[5]" and returns 10.
Explanation: Moving cache inside memoize gives each memoized function its own private cache via closure.
Key Insight: State inside a factory function is private to each returned function — this is the closure encapsulation pattern.