Currying & Memoization — JavaScript interview guide
Currying & Memoization
Currying turns f(a, b, c) into f(a)(b)(c). Memoization caches results so the same input is not computed twice. Both rely on closures.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Memoization: the cache lives in a closure
1function memoize(fn) {2const cache = {};3return (n) => {4if (n in cache) return cache[n];5return (cache[n] = fn(n));6};7}8▶const square = memoize((n) => {10console.log("computing", n);11return n * n;12});1314console.log(square(4));15console.log(square(4));
| square | ƒ memoized |
| fn | ƒ (n) => n*n |
| cache | {} |
nothing printed yet
What happens:memoize returns a new function. Through a closure it keeps two things: the original fn and an empty cache object.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Currying
Useful for creating specialised functions from general ones.
const curry = (fn) =>
function curried(...args) {
return args.length >= fn.length
? fn(...args)
: (...next) => curried(...args, ...next);
};
const add = curry((a, b, c) => a + b + c);
add(1)(2)(3); // 6
add(1, 2)(3); // 6Infinite currying: sum(1)(2)(3)()
A favourite interview twist: keep returning a function until called with no argument.
const sum = (a) => (b) => (b === undefined ? a : sum(a + b));
sum(1)(2)(3)(); // 6Memoization
Store results in a cache inside a closure, keyed by the arguments.
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;
};
}Remember this
- fn.length gives the number of declared parameters.
- Memoize only pure functions.
- React.memo and useMemo are memoization ideas too.
Interview questions
Where is currying useful in real code?
Creating pre-configured helpers, e.g. a logger(level)(message), event handlers with fixed ids, or partial application in functional utilities.
Practice
- Make sum(1)(2)(3) also work with sum(1, 2)(3)().
- Memoize a recursive Fibonacci and compare timings.
Keep learning
More in Functions & Objects