FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Memoize II

25mins

Implement a function memoize(fn) that returns a memoized version of the given function.

The function should:

  • Accept a function fn that can take any number of arguments.
  • Cache the results of previous calls based on the arguments.
  • Return the cached result if the function is called again with the same arguments.
  • Work for primitive arguments and arrays (use JSON.stringify for cache key generation).

Example

function add(a, b) { console.log("computing..."); return a + b; } const memoizedAdd = memoize(add); memoizedAdd(1, 2); // "computing..." 3 memoizedAdd(1, 2); // 3, retrieved from cache

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests