Composition and Memoisation
Composing small functions into a pipeline, and caching results so expensive work happens once.
compose and pipe build one function from several, reading right to left or left to right. Memoisation trades memory for time by by argument, and choosing the cache key is the part that goes wrong. A WeakMap keyed by object avoids the leak a Map creates.
EXERCISE
1Building a Pipeline
Two helpers turn a sequence of small transformations into a single named function.
The problem with nesting:
const result = capitalise(trim(toLowerCase(input)));
Three transformations, read right to left, with the data buried in the middle. Add two more and it becomes unreadable.
pipe runs left to right:
function pipe(...fns) {
return function (input) {
return fns.reduce((value, fn) => fn(value), input);
};
}
const normalise = pipe(toLowerCase, trim, capitalise);
console.log(normalise(" ADA ")); // Ada
One line, in the order things happen, and normalise is now a name you can reuse and test.
compose runs right to left, matching the maths convention:
function compose(...fns) {
return function (input) {
return fns.reduceRight((value, fn) => fn(value), input);
};
}
const normalise = compose(capitalise, trim, toLowerCase);
Same result, reversed argument order. reduce against reduceRight is the only difference in the implementation, which is a neat demonstration that the two helpers are one idea.
What composition requires of the functions:
// Each takes one argument and returns one value.
// No side effects, so order changes nothing unexpectedly.
// The output type of each matches the input of the next.
That last one is why composition and currying are usually taught together: a curried function that takes its data last is already the right shape.
const prop = (key) => (obj) => obj[key];
const upper = (s) => s.toUpperCase();
const loudName = pipe(prop("name"), upper);
console.log(loudName({ name: "ada" })); // ADA
And an async version, since pipelines often involve waiting:
function pipeAsync(...fns) {
return function (input) {
return fns.reduce(
(promise, fn) => promise.then(fn),
Promise.resolve(input),
);
};
}
const loadAndFormat = pipeAsync(fetchUser, extractName, capitalise);
const name = await loadAndFormat(userId);
Each step receives the resolved value of the previous one, because a .then callback returning a promise is waited for, as Unit 5 established. Synchronous steps work in the same chain with no special handling.
Pro Tip: Prefer
pipeovercomposeunless you have a reason. Reading left to right matches the order the transformations actually happen and matches every other chain in the language, from.map().filter()to a shell pipeline.composeexists because mathematical notation goes the other way, which is a poor reason to make your code harder to read.
EXERCISE
2Memoisation, and Choosing the Key
Caching by arguments is simple until the arguments are not strings, which is where most implementations quietly break.
The basic idea:
function memoise(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const slowSquare = (n) => {
for (let i = 0; i < 1e7; i++) {}
return n * n;
};
const fastSquare = memoise(slowSquare);
console.log(fastSquare(5)); // slow
console.log(fastSquare(5)); // instant
Now the three things wrong with JSON.stringify as a key:
// 1. Key order changes the string
JSON.stringify({ a: 1, b: 2 }); // '{"a":1,"b":2}'
JSON.stringify({ b: 2, a: 1 }); // '{"b":2,"a":1}'
// Two equivalent objects, two cache entries.
// 2. Some values do not survive
JSON.stringify([undefined, () => {}, new Date()]);
// '[null,null,"2026-09-21T..."]'
// undefined and functions become null; a Date becomes a string.
// 3. It is slow for large arguments, which can cost more
// than the function you are caching.
For a single primitive argument, skip it entirely:
function memoiseOne(fn) {
const cache = new Map();
return function (arg) {
if (!cache.has(arg)) {
cache.set(arg, fn.call(this, arg));
}
return cache.get(arg);
};
}
A Map compares keys by identity for objects and by value for primitives, which is exactly right here and needs no serialisation.
For a single object argument, use a WeakMap:
function memoiseByObject(fn) {
const cache = new WeakMap();
return function (obj) {
if (!cache.has(obj)) {
cache.set(obj, fn.call(this, obj));
}
return cache.get(obj);
};
}
const analyse = memoiseByObject((config) => expensiveAnalysis(config));
This is the Unit 9 point arriving where it belongs. A Map here would hold every config object forever, so the cache becomes a leak that grows with every distinct input. The WeakMap version lets an entry disappear as soon as the object does, and needs no eviction logic at all.
And the caches that need a bound:
// Memoising a pure function of one small primitive: usually safe.
// Memoising anything called with unbounded distinct inputs:
// needs a maximum size, a time limit, or weak keys.
function memoiseWithLimit(fn, max = 100) {
const cache = new Map();
return function (arg) {
if (cache.has(arg)) return cache.get(arg);
const result = fn.call(this, arg);
cache.set(arg, result);
if (cache.size > max) {
cache.delete(cache.keys().next().value); // drop the oldest
}
return result;
};
}
A Map preserves insertion order, so the first key from its iterator is the oldest. That is a simple least-recently-inserted eviction in two lines.
When not to memoise:
// The function is cheap. The cache lookup costs more.
// The function has side effects. They now happen once.
// The function is not pure. The cached answer goes stale.
Pro Tip: Before memoising, check that the function is genuinely pure and genuinely expensive. Most memoisation in real codebases caches something cheap, keyed by a stringify that costs more than the call, and holds memory forever. Measure first; the technique is correct and the instinct for when to apply it is usually wrong.
EXERCISE
3Purity, and Why These Techniques Need It
Composition, memoisation and most of this unit assume functions that only use their arguments, which is worth stating explicitly.
Every technique in this unit works because of a property that has been assumed rather than named.
A pure function:
// Uses only its arguments. Returns the same output for the same
// input. Changes nothing outside itself.
function add(a, b) {
return a + b;
}
function formatPrice(paise) {
return `Rs ${(paise / 100).toFixed(2)}`;
}
An impure one:
let total = 0;
function addToTotal(n) {
total += n; // changes something outside
return total;
}
function greet() {
return `Hello, it is ${Date.now()}`; // different every call
}
function save(user) {
db.write(user); // side effect
}
Why each technique needs it:
// Memoisation: caches by input. An impure function returns
// something different for the same input, so the
// cache is wrong rather than merely stale.
// Composition: each step gets only the previous output. A step
// reading outside state breaks when the pipeline
// is reordered or reused.
// Currying: a curried function may be called much later, with
// its early arguments captured. Anything it reads
// from outside may have changed by then.
Purity is doing more work in this unit than it first appears. It is the reason a composed pipeline can be reordered safely, the reason a memoised result stays correct, and the reason a curried function captured an hour ago still behaves. Every one of those guarantees disappears the moment a function reads something it was not given.
Which does not mean avoiding side effects:
// A program with no side effects does nothing observable.
// The aim is to concentrate them, not eliminate them.
// Pure core:
const nextState = applyAction(state, action);
const summary = formatSummary(nextState);
// Impure edge:
render(summary);
await db.save(nextState);
Calculations in the middle, effects at the boundary. The pure part is testable with no setup, reusable anywhere, and safe to memoise or compose. The impure part is small and obvious.
A practical test for a function you are unsure about:
// Could you call it twice in a row with the same arguments and
// safely throw the first result away?
//
// Yes -> pure, and everything in this unit applies.
// No -> impure, and it belongs at the edge.
That test is more reliable than trying to a function by reading it, because the impurity is often somewhere you are not looking: a logger, a cache, a timestamp, a randomiser, or an argument quietly modified in place.
And the one that catches people:
function addItem(cart, item) {
cart.items.push(item); // mutates the argument
return cart;
}
function addItemPure(cart, item) {
return { ...cart, items: [...cart.items, item] };
}
The first changes something the caller still holds, which is Unit 1's reads-climb-writes-land point seen from the other side. It is impure even though it touches nothing global, and it is the most common way a function that looks pure is not.
