Typorithm · medium

Cache Keys for Many Args

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

Step 1 of 8 · intro card

Learn Cache Keys for Many Args

0%

Memoization

Functions with multiple arguments need a composite cache key. Collecting args with rest params and serializing them with JSON.stringify builds one string key — but watch for argument order, non-serializable values, and object identity.

A single-argument cache keyed by n breaks for multi-arg functions, since two different argument lists could collide or be impossible to key. Rest params gather every argument into an args array.

JSON.stringify(args) flattens that array into one deterministic string, which becomes the Map key. Identical argument lists serialize to identical keys, so repeat calls hit the cache.

Pitfalls: the key depends on argument order; functions, undefined, symbols, and circular structures do not serialize cleanly; and two equal-looking objects with different contents are distinguished only by their serialized form, not identity. Alternatives include a nested Map per argument or a WeakMap when keying by object reference.

01

Multi-arg functions need a composite key.

02

JSON.stringify(args) builds one string key from rest params.

03

Pitfalls: arg order, non-serializable args, object identity.

function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const value = fn(...args);
    cache.set(key, value);
    return value;
  };
}

Read the implementation

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

1. Rest params

Collecting all arguments into an args array lets the wrapper support any arity.

return (...args) => {

2. Composite key

JSON.stringify turns the args array into one string usable as a single Map key.

const key = JSON.stringify(args);

3. Keyed hit

The serialized key looks up a prior result for the exact same argument list.

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

4. Spread args

Spreading args back out passes the original arguments through to fn unchanged.

const value = fn(...args);

5. Store by key

The result is stored under the composite string key for future lookups.

cache.set(key, value);

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.

Cache Keys for Many Args: Lesson & Practice · Typorithm | ApplyDjinn