1. Result cache
A Map in the closure stores results keyed by the call's arguments.
const cache = new Map();Typorithm · medium
Step 1 of 8 · intro card
Utility Functions
memoize wraps fn so repeated calls with the same arguments return a cached result instead of recomputing. A Map keyed by the serialized arguments holds previous results.
memoize returns a wrapper that caches fn's output. The first call with a given set of arguments computes and stores the result; later calls with the same arguments return the cached value instantly.
The cache is a Map living in the closure. Arguments are serialized with JSON.stringify to form a stable key, so [1, 2] always maps to the same cache entry.
It only pays off for pure functions — those whose output depends solely on their inputs and have no side effects — otherwise stale cached values cause bugs.
Caches results by argument key.
Returns the cached value on a repeat call.
Only safe for pure functions.
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}Connect each part of the code to the concept before you type.
A Map in the closure stores results keyed by the call's arguments.
const cache = new Map();Serializing the arguments produces a stable string key for the cache.
const key = JSON.stringify(args);If the key exists, return the stored result without calling fn again.
if (cache.has(key)) return cache.get(key);On a miss, compute fn and store the result under its key for next time.
cache.set(key, 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.