167
Top Answer
Memoization caches function results based on arguments to avoid redundant calculations.
Implementation
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
// Usage
const expensiveFn = memoize((n) => {
console.log('Computing...');
return n * 2;
});
expensiveFn(5); // Computing... 10
expensiveFn(5); // 10 (cached)
When to Use:
✅ Pure functions with expensive calculations ✅ Recursive algorithms (Fibonacci, factorial) ✅ Functions called repeatedly with same args
When NOT to Use:
❌ Functions with side effects ❌ Functions with many unique inputs (cache grows forever) ❌ Simple calculations (overhead > benefit)
OptimizationPro