1. The cache
A Map created once per memoize() call holds computed results keyed by input.
const cache = new Map();Typorithm · medium
Step 1 of 8 · intro card
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.
memoize() wraps a pure fn and caches results by input.
The Map closure persists across calls.
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;
};
}Connect each part of the code to the concept before you type.
A Map created once per memoize() call holds computed results keyed by input.
const cache = new Map();The returned arrow function closes over cache, so the cache persists across every call.
return (n) => {When the input was seen before, return the stored value and skip recomputation entirely.
if (cache.has(n)) return cache.get(n);On a miss, call the wrapped function once to produce the result.
const result = fn(n);Save the computed result under its input key so the next call with the same n is a hit.
cache.set(n, result);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.