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)
  1. Use a Map or object to store cached results.
  2. Create a unique key from the function arguments.
  3. For simple cases, JSON.stringify(args) works as a key.
  4. Check if the key exists in cache before computing.
  5. Store the result in cache after computing.

Topics

  • Performance

Asked at

Google · Meta · Netflix · Uber

Join Us
blur