Frontend101 logoFrontend101
← Problems
#6EasyJavaScript functions

6. Memoize

JavaScriptClosures & Scope

Implement a memoize(fn) higher-order function that caches results based on input arguments.

Example 1:
const memoSum = memoize((a, b) => a + b);
memoSum(2, 3); // computed -> 5
memoSum(2, 3); // cached   -> 5
solution.js
Caches repeated calls with same arguments
(() => {
          let calls = 0;
          const add = memoize((a, b) => { calls++; return a + b; });
          expect(add(2, 3)).toBe(5);
          expect(add(2, 3)).toBe(5);
          expect(add(4, 5)).toBe(9);
          expect(calls).toBe(2);
        })()