Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Memoize a Function

A Closer Look at Functionshard

Course · Section 10: A Closer Look at Functions · Lecture 139: Functions Returning Functions

Implement `memoize(fn)` returning a function that caches results by arguments, so `fn` runs only once per distinct argument list.

Examples

Input: slow doubles and logs calls; m = memoize(slow); m(2), m(2), m(3)
Output: results [4, 4, 6], underlying calls [2, 3]
Repeated arguments hit the cache, so slow runs only for 2 and 3.

Sample tests

Input: caches by arguments
Output: [[4,4,6,6,4],[2,3]]
Input: multiple arguments
Output: [[3,3],[[1,2]]]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A cache keyed only by the first argument breaks multi-argument functions.
  • Recomputing on a hit defeats memoization.
Visualize this concept: Currying →
Approach & explanation (try first)

A closure-held Map keyed by the stringified arguments caches results, so the wrapped function runs once per distinct input.

Loading...
⌘/Ctrl + Enter

Run your code to see results.