Description

Calling the same function repeatedly with the same arguments can be inefficient, especially if the function performs expensive computations.

To optimize this, developers use memoization — a technique that caches results so that repeated calls with the same inputs return instantly.

In this challenge, you’ll implement a memoize function that caches the results of function calls.


Your Task

Implement a function memoize(fn) that:

  • Accepts a function fn
  • Returns a new function
  • Caches the result based on input arguments
  • Returns cached results for repeated calls with the same arguments
  • Preserves the this context
  • Works for multiple arguments

Example

Input

const slowAdd = (a, b) => {
console.log('computing...');
return a + b;
};

const memoizedAdd = memoize(slowAdd);

memoizedAdd(2, 3);
memoizedAdd(2, 3);
memoizedAdd(4, 5);

Output

computing...
computing...

(Return values are 5, 5, and 9)


Expected Behavior

  • Function executes only once per unique argument set
  • Cached results are reused
  • Supports multiple arguments
  • Preserves this context
  • Original function is not modified

Constraints

  • Do not use global variables
  • Time complexity: O(1) for cached calls
  • Space complexity grows with number of unique inputs