MediumJavaScriptTypeScript

Memoize Pure Functions

Functional ProgrammingMemoizationPerformance

Memoization caches the result of a pure function so repeated calls with the same arguments are instant.

// without memoize — fib(35) recomputes every sub-problem millions of times
function fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}

// with memoize — each sub-problem computed once
const fib = memoize(function fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
});

Implement memoize(fn) that caches results keyed by the serialised arguments.

Sample tests

Test #1fib(10) = 55
Input: [10,"fib"]
Output: 55
Test #2fib(0) = 0
Input: [0,"fib"]
Output: 0
Test #3factorial(5) = 120
Input: [5,"factorial"]
Output: 120