Implement Memoization
MediumPerformance15 min4 tests
Implement a memoize function that caches the results of function calls.
Requirements
- Cache results based on arguments
- Return cached result for repeated calls with same arguments
- Handle multiple arguments
- Optional: Support a custom key generator
Example
const expensiveFn = memoize((n) => {
console.log('Computing...');
return n * 2;
});
expensiveFn(5); // logs "Computing...", returns 10
expensiveFn(5); // returns 10 (no log, cached)Hints (5)
- Use a Map or object to store cached results.
- Create a unique key from the function arguments.
- For simple cases,
JSON.stringify(args)works as a key. - Check if the key exists in cache before computing.
- Store the result in cache after computing.
Topics
- Performance
Asked at
Google · Meta · Netflix · Uber
