Typorithm · medium

memoize

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

Step 1 of 8 · intro card

Learn memoize

0%

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.

01

Caches results by argument key.

02

Returns the cached value on a repeat call.

03

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;
  };
}

Read the implementation

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

1. Result cache

A Map in the closure stores results keyed by the call's arguments.

const cache = new Map();

2. Build the key

Serializing the arguments produces a stable string key for the cache.

const key = JSON.stringify(args);

3. Cache hit

If the key exists, return the stored result without calling fn again.

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

4. Store the result

On a miss, compute fn and store the result under its key for next time.

cache.set(key, 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: Lesson & Practice · Typorithm | ApplyDjinn