JavaScript
CHALLENGE
const memoize = (fn) => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
};
let calls = 0;
const square = memoize((x) => {
calls++;
return x * x;
});
console.log(square(4), square(4), square(-4), calls);
1.5K ·