Typorithm · medium

memoize() Higher-Order Fn

memoize-basicpatternsmemoizecacheclosure
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn memoize() Higher-Order Fn

0%

Memoization

memoize() is a higher-order function that wraps a pure function and caches its results in a Map keyed by input. A repeat call with the same input returns the cached value and skips recomputation, trading memory for speed.

memoize() takes a function fn and returns a new function with the same signature. Internally it keeps a Map (the cache) that the returned closure captures, so the cache lives as long as the wrapper does.

On each call it checks the cache: a hit returns the stored value immediately; a miss calls fn(n) once, stores the result, and returns it. Repeated inputs are answered from memory instead of recomputed.

This only works for pure, deterministic functions — ones whose output depends solely on the input with no side effects. Caching the result of an impure function (random, time-based, or I/O) would return stale or wrong answers.

01

memoize() wraps a pure fn and caches results by input.

02

The Map closure persists across calls.

03

A cache hit skips recomputation; it trades memory for speed.

function memoize(fn) {
  const cache = new Map();
  return (n) => {
    if (cache.has(n)) return cache.get(n);
    const result = fn(n);
    cache.set(n, result);
    return result;
  };
}

Read the implementation

Connect each part of the code to the concept before you type.

1. The cache

A Map created once per memoize() call holds computed results keyed by input.

const cache = new Map();

2. Returned closure

The returned arrow function closes over cache, so the cache persists across every call.

return (n) => {

3. Cache hit

When the input was seen before, return the stored value and skip recomputation entirely.

if (cache.has(n)) return cache.get(n);

4. Cache miss

On a miss, call the wrapped function once to produce the result.

const result = fn(n);

5. Store result

Save the computed result under its input key so the next call with the same n is a hit.

cache.set(n, result);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

memoize() Higher-Order Fn: Lesson & Practice · Typorithm | ApplyDjinn