1. Rest params
Collecting all arguments into an args array lets the wrapper support any arity.
return (...args) => {Typorithm · medium
Step 1 of 8 · intro card
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.
Multi-arg functions need a composite key.
JSON.stringify(args) builds one string key from rest params.
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;
};
}Connect each part of the code to the concept before you type.
Collecting all arguments into an args array lets the wrapper support any arity.
return (...args) => {JSON.stringify turns the args array into one string usable as a single Map key.
const key = JSON.stringify(args);The serialized key looks up a prior result for the exact same argument list.
if (cache.has(key)) return cache.get(key);Spreading args back out passes the original arguments through to fn unchanged.
const value = fn(...args);The result is stored under the composite string key for future lookups.
cache.set(key, value);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.