Codetive
Sign In
Coding challenges as of now are only available on desktop
On mobile you can try our quiz
Quiz
We are working hard to bring coding challenges with editor on mobile 💚

Memoize Function

Objective: Implement a memoization function that caches the results of function calls to improve performance.

Instructions:

  1. Create a function named memoize that takes a function as an argument and returns a new function that caches the results of the function.
  2. The memoized function should store the results of previous calls and return the cached result when the same arguments are provided.
  3. The function should only recompute the result if the arguments have changed.

Example Usage:

const slowFunction = (num) => {
  // Simulate a slow computation
  return new Promise((resolve) => {
    setTimeout(() => resolve(num * 2), 3000); // Simulates a 3-second delay
  });
};
 
const memoizedFunction = memoize(slowFunction);
 
memoizedFunction(5).then(result => console.log(result));  // Calls slowFunction, outputs: 10 after 3 seconds
memoizedFunction(5).then(result => console.log(result));  // Returns cached result, outputs: 10 immediately

Requirements:

  • The memoize function should cache the result of previous function calls based on the arguments provided.
  • When called with the same arguments, the function should return the cached result instead of recomputing it.
  • The cache should clear or replace old values when new ones are computed.

Hints:

  1. Use an object or Map to store the function arguments and their corresponding results.
  2. Consider how you will handle multiple arguments and different types of data.

Bonus:

  1. Implement a cache size limit, where the oldest cached result is removed when the cache reaches its limit.
  2. Add support for handling multiple arguments and deep comparisons of objects.
Browser
Console
Tests
Soon