Implement a simple memoization decorator.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
Memoization is an optimization technique where the results of expensive function calls are cached.
1. Create a higher-order function that takes the original function (fn) as input.
2. Inside, create a cache (e.g., a Map).
3. Return a new function that:
function memoize(fn) {
const cache = new Map();
return function(...args) {
// A simple key for primitive arguments. For objects, JSON.stringify would be better.
const key = args.join('-');
if (cache.has(key)) {
console.log('Fetching from cache...');
return cache.get(key);
}
console.log('Calculating result...');
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
function slowAdd(a, b) {
// Simulate slow calculation
for (let i = 0; i < 1e8; i++) {}
return a + b;
}
const memoizedAdd = memoize(slowAdd);
memoizedAdd(2, 3); // Calculates
memoizedAdd(2, 3); // Fetches from cache