Functional Programming Questions
Functional programming as a paradigm and a way of structuring code: pure functions and side-effect isolation (a pure core with effects at the edges, and how effects are described versus run), immutability and persistent data structures with structural sharing, updating nested immutable data including lenses, higher-order functions, function composition, currying and partial application, folds and recursion over data (including tail recursion), algebraic data types and pattern matching, total functions and Maybe/Either style error values, functors, applicatives and monads as patterns for composing effects and threading state, parser combinators as a worked example, lazy evaluation and lazy or streaming pipelines, and property-based testing of pure code. Covers reasoning about programs as composed transformations rather than mutable state, in a dedicated functional language such as Haskell or Scala, or in a multi-paradigm language such as JavaScript, TypeScript, Kotlin or Python. Boundary: closures and the this binding as language mechanics, the event loop and reactive streams, threads and STM-style concurrency, performance profiling, and exception or resource handling are covered elsewhere.
Your team is debating whether a small UI widget that keeps a counter and re-renders a view should be written with classes and mutable fields or as plain functions over immutable state. Sketch both versions in JavaScript or TypeScript, then tell me which you would ship and what you would give up by choosing it.
Sample Answer
Direct answer
I would ship the functional version: state is an immutable value, a pure reducer (a function (state, action) => newState) is the only code that decides what the next state is, a view function turns state into output, and a few lines of mutable shell connect it to the page. I would give up a little brevity and some in-place speed, and I would keep a class only for the parts that own a resource (a socket, a timer, a canvas). Run on the same steps, the two versions show the difference in testability and in how exposed the state is.
Both versions
// ---------- Version A: class with mutable fields ----------
class CounterWidget {
private count = 0;
history: number[] = [];
constructor(private root: { text: string }) {}
increment(): void {
this.history.push(this.count);
this.count += 1;
this.render();
}
undo(): void {
const prev = this.history.pop();
if (prev !== undefined) this.count = prev;
this.render();
}
private render(): void {
this.root.text = `Count: ${this.count}`;
}
}
// ---------- Version B: plain functions over immutable state ----------
type State = { readonly count: number; readonly history: readonly number[] };
type Action = { type: "increment" } | { type: "undo" };
const initial: State = { count: 0, history: [] };
const reduce = (s: State, a: Action): State => {
switch (a.type) {
case "increment":
return { count: s.count + 1, history: [...s.history, s.count] };
case "undo": {
if (s.history.length === 0) return s;
return { count: s.history[s.history.length - 1], history: s.history.slice(0, -1) };
}
}
};
const view = (s: State): string => `Count: ${s.count}`;
// the thin imperative shell: the only place with mutation and effects
const mount = (root: { text: string }) => {
let state = initial;
const dispatch = (a: Action) => {
const next = reduce(state, a);
if (next === state) return; // nothing changed, skip the re-render
state = next;
root.text = view(state);
};
root.text = view(state);
return dispatch;
};
// ---------- Checks ----------
let failures = 0;
const eq = (label: string, got: unknown, want: unknown) => {
const ok = JSON.stringify(got) === JSON.stringify(want);
if (!ok) failures++;
console.log((ok ? "pass " : "FAIL ") + label + ": " + JSON.stringify(got));
};
// B needs no widget, no root, no setup: input state and action, output state
const s1 = reduce(initial, { type: "increment" });
const s2 = reduce(s1, { type: "increment" });
eq("B reduce twice", s2, { count: 2, history: [0, 1] });
eq("B old state untouched", s1, { count: 1, history: [0] });
eq("B undo on empty returns same object", reduce(initial, { type: "undo" }) === initial, true);
eq("B view", view(s2), "Count: 2");
const rootB = { text: "" };
const dispatch = mount(rootB);
dispatch({ type: "increment" });
dispatch({ type: "increment" });
dispatch({ type: "undo" });
eq("B mounted", rootB.text, "Count: 1");
// The skip-render guard in dispatch: count how often the view is written
let writes = 0;
const rootC = { get text() { return ""; }, set text(_v: string) { writes++; } };
const dispatchC = mount(rootC); // initial render: 1 write
dispatchC({ type: "undo" }); // reducer returns the same state: no write
dispatchC({ type: "increment" }); // new state: 1 write
eq("B skips the render when nothing changed", writes, 2);
// A needs a root object and drives it through methods
const rootA = { text: "" };
const w = new CounterWidget(rootA);
w.increment();
w.increment();
w.undo();
eq("A mounted", rootA.text, "Count: 1");
// the cost of exposed mutable state: any holder of `history` can corrupt the widget
const leaked = w.history;
leaked.push(999);
w.undo();
eq("A after outside code pushed to history", rootA.text, "Count: 999");
if (failures > 0) throw new Error(failures + " checks failed");
Compiled and run (TypeScript 5, node:22 container):
npx -y -p typescript@5 tsc --strict --target es2022 --module commonjs --outDir out counter.ts
node out/counter.js
pass B reduce twice: {"count":2,"history":[0,1]}
pass B old state untouched: {"count":1,"history":[0]}
pass B undo on empty returns same object: true
pass B view: "Count: 2"
pass B mounted: "Count: 1"
pass B skips the render when nothing changed: 2
pass A mounted: "Count: 1"
pass A after outside code pushed to history: "Count: 999"
The eq helper counts every mismatch and the last line of the file throws if any were counted. The checks at the end are both a test and the argument. Two of them guard the claims made below: deleting the if (s.history.length === 0) return s; line makes the undo-on-empty check print FAIL, and deleting the if (next === state) return; line in dispatch makes the render-count check print FAIL (3 writes instead of 2).
The trade-offs, against the code
- Testability.
reducetakes a value and returns a value: the fourBchecks need no widget, no root element and no setup, and each one sets its own input. The class needs arootto be constructed and is driven by calling methods in order, so a test reads as a story rather than an assertion, and tests that share an instance can leak into each other. - Mutability. The class keeps
historyas a public array so the demo can show the hazard: the last check pushes999into it from outside and the nextundo()sets the count to 999. Makinghistoryprivate closes that hole, but the underlying issue stays: any method can change state in place, so you must read every method to know what can happen. In version B,reduce(s1, ...)leavess1untouched (the "old state untouched" check), so undo, time travel (stepping the app backward and forward through earlier states, which is possible because every past state is still intact) and "did anything change?" (next === state) come for free. - Composition. Reducers combine by calling each other on slices of state; views combine as ordinary function calls. Class widgets combine by holding references to each other, which tends to spread state across objects.
- Maintainability. Version B puts every state change in one
switch, which is the place to look when a bug report says "the count is wrong". The cost is that adding a feature means adding an action type and a case, more lines thanthis.count += 1. - What you give up. (1) Ceremony: actions, a union type, a dispatch shell. (2) Allocation: every update creates a new state object. For a counter this is nothing; for large state updated thousands of times per second it can matter, and you would then use structural sharing (the new state reuses every unchanged part of the old one by reference and copies only the path that changed) or Immer (a library that lets you write ordinary mutating code against a temporary draft and returns a new immutable state with structural sharing). (3)
readonlyin TypeScript is a compile-time promise only, not enforced at runtime, so a strayas anycan still mutate. (4) Teammates who think in objects need a short ramp.
They blend in practice
The functional core is exactly what frameworks ask of you. React's useReducer takes the same (state, action) function, and its documentation says the reducer must be pure and must not mutate state: if you return the same object, React skips re-rendering, which is the same next === state check the shell does above. A hook-based component is a function over state, and a class is still the right tool for a thing with identity and a lifecycle, such as a Web Component (a custom HTML tag you define yourself, for example <my-counter>, by writing a class that extends the browser's built-in HTMLElement base class, which the browser instantiates and then notifies when it is attached to or removed from the page). The decision is "where does the state change logic live", not "classes or functions everywhere".
What would flip the choice
Choose the class if the widget owns a resource with setup and teardown, if the codebase and its tests are already object-oriented and consistency is worth more, or if profiling shows allocation per update is a measured cost. For a counter and a view with history, B is smaller to reason about and easier to test.
What is the difference between function composition, currying and partial application? Write a compose helper and a curry helper in a language you know, and show how they change the way you design function signatures and argument order.
Sample Answer
Direct answer
- Composition joins functions end to end:
compose(f, g)(x)isf(g(x)). It is about the flow of one value through several steps. - Currying rewrites a function of several arguments into a chain of functions that each take one:
f(a, b, c)becomesf(a)(b)(c). It is a change in the shape of a single function. - Partial application fixes some arguments of a function now and returns a function waiting for the rest:
partial(f, a, b)gives(c) => f(a, b, c). It is an operation you apply to a function.
Currying makes partial application cheap (calling a curried function with one argument is a partial application), and both exist to produce small one-argument functions that composition can chain. They are three ideas, not three names for one.
Helpers, run
// compose: right to left, one input flows through
const compose = (...fns) => (x) => fns.reduceRight((acc, f) => f(acc), x);
const pipe = (...fns) => (x) => fns.reduce((acc, f) => f(acc), x);
// curry: turns f(a, b, c) into f(a)(b)(c) (also accepts f(a, b)(c) etc.)
const curry = (f) => function curried(...args) {
return args.length >= f.length ? f(...args) : (...more) => curried(...args, ...more);
};
// partial application: fix some arguments now, supply the rest later
const partial = (f, ...preset) => (...rest) => f(...preset, ...rest);
const add3 = (a, b, c) => a + b + c;
console.log("curried:", curry(add3)(1)(2)(3), curry(add3)(1, 2)(3), curry(add3)(1)(2, 3));
console.log("partial:", partial(add3, 1, 2)(3));
console.log("curry is not partial: curry(add3)(1) is a", typeof curry(add3)(1), "that still needs 2 more calls");
const inc = (x) => x + 1, dbl = (x) => x * 2;
console.log("compose(dbl, inc)(5) =", compose(dbl, inc)(5), "| pipe(dbl, inc)(5) =", pipe(dbl, inc)(5));
// Argument order: put the data last so partial application yields reusable functions
const mapBad = (arr, f) => arr.map(f); // data first
const map = curry((f, arr) => arr.map(f)); // data last
const filter = curry((p, arr) => arr.filter(p));
const sumSquaresOfEvens = pipe(filter((n) => n % 2 === 0), map((n) => n * n), (a) => a.reduce((s, n) => s + n, 0));
console.log("sumSquaresOfEvens([1..6]) =", sumSquaresOfEvens([1, 2, 3, 4, 5, 6]));
const double = map(dbl);
console.log("double([1,2,3]) =", double([1, 2, 3]), "| data-first needs a wrapper:", ((arr) => mapBad(arr, dbl))([1, 2, 3]));
// Pitfall: curry reads f.length, which ignores default and rest parameters
const withDefault = (a, b = 10) => a + b;
const withRest = (a, ...rest) => a + rest.length;
console.log("lengths:", add3.length, withDefault.length, withRest.length);
console.log("curry(withDefault)(1) =", curry(withDefault)(1), "(called immediately with b = 10)");
Run in a node:22 container it prints:
curried: 6 6 6
partial: 6
curry is not partial: curry(add3)(1) is a function that still needs 2 more calls
compose(dbl, inc)(5) = 12 | pipe(dbl, inc)(5) = 11
sumSquaresOfEvens([1..6]) = 56
double([1,2,3]) = [ 2, 4, 6 ] | data-first needs a wrapper: [ 2, 4, 6 ]
lengths: 3 1 1
curry(withDefault)(1) = 11 (called immediately with b = 10)
How the helpers work:
- Start with
curry(add3)(1)(2)(3)traced call by call.f.lengthis 3 (the number of parametersadd3declares).curried(1)has collected 1 argument, 1 < 3, so it returns a new function that remembers1. Calling that with2runscurried(1, 2): 2 < 3, another waiting function. Calling that with3runscurried(1, 2, 3): 3 >= 3, so it finally callsadd3(1, 2, 3)and returns 6. compose(...fns)reduces from the right, socompose(dbl, inc)(5)appliesincfirst (6) and thendbl(12).pipeis the same list read left to right, givingdbl(5)= 10 theninc= 11. Choosepipewhen you want code to read in execution order; the two differ only in direction.currycompares the number of arguments collected so far withf.length(the declared parameter count) and either callsfor returns a function that collects more. Because thecurriedfunction accepts several arguments per call,curry(add3)(1, 2)(3)works too. This is the usual JavaScript flavour; in a strictly one-argument-at-a-time curry,(1, 2)would not be allowed.partial(f, ...preset)stores the preset arguments in a closure (a function that remembers the variables around where it was created) and prepends them when the rest arrive. It can fix any number of arguments but only from the left. Fixing a middle argument needs a wrapper arrow function such as(b) => f(1, b, 3), or a library helper that accepts a placeholder value marking which argument stays open.
How it changes signature and argument-order design
Composition feeds one value into the next function, so steps work best when they take one input in the position the pipeline supplies. Therefore:
- Put the data last and configuration first.
map(f)(arr)andfilter(p)(arr)can be configured once and then dropped into apipe. In the exampledouble = map(dbl)is a reusable function; with the built-in data-first shapemapBad(arr, f)you need a wrapper arrow function every time (the sixth output line).sumSquaresOfEvensis a pipeline of the curriedfilterandmapplus one plain reducing step. - Order parameters from most stable to most variable. The thing you will apply many times (the formatter, the predicate, the base URL) comes first.
- Prefer one input and one output per step. Several related values travel better as one object parameter than as a long positional list, because a long positional list makes currying order matter.
- Keep the shape predictable. A function whose result type changes depending on how many arguments you give it is hard to type in TypeScript and hard to compose.
In Haskell every function is curried by default: add3 :: Int -> Int -> Int -> Int really is a function from Int to a function, so partial application is just calling with fewer arguments, and composition is the . operator.
add3 :: Int -> Int -> Int -> Int
add3 a b c = a + b + c
main :: IO ()
main = do
let f = add3 1 -- partial application is just calling with fewer arguments
print (f 2 3)
print ((subtract 1 . (* 2)) 5) -- composition: (* 2) first, then subtract 1
6
9
(subtract 1 . (* 2) doubles first, then subtracts one: 5 gives 10 then 9.)
Pitfalls
f.lengthlies. The output linelengths: 3 1 1shows that default and rest parameters are not counted:withDefault(a, b = 10)reports 1, socurry(withDefault)(1)calls it immediately and returns 11 instead of waiting forb. Thecurryshown above has no way to override that, so a helper based onf.lengthneeds a variant that takes an explicit arity (the number of arguments a function expects) for functions with defaults or rest parameters:
const curryN = (f, n = f.length) => function curried(...args) {
return args.length >= n ? f(...args) : (...more) => curried(...args, ...more);
};
console.log(typeof curryN(withDefault, 2)(1), curryN(withDefault, 2)(1)(5));
Run in a node:22 container (after the definitions above) it prints function 6: with the arity stated as 2, curryN(withDefault, 2)(1) waits instead of reading the declared 1.
- Extra arguments from callers. Passing a curried function straight into
maphands it(element, index, array), which can trigger early evaluation. Withadd = curry((a, b) => a + b),[1, 2, 3].map(add)callsadd(1, 0, [1, 2, 3]): three arguments are at least the 2 needed, soaddruns at once and adds the index, giving[1, 3, 5]instead of three waiting functions. Run in anode:22container,[1, 2, 3].map(add)prints[ 1, 3, 5 ]while[1, 2, 3].map(add(10))prints[ 11, 12, 13 ]. Wrap it, as inmap((x) => add(x)(10)), or limit the arity by passing only the one argument you mean ((x) => f(x)). - Debuggability. Deep pipelines give anonymous stack frames; name the steps and consider a small
tap(console.log)step while debugging. - Overuse. Curry what you actually reuse. A currying helper everywhere makes TypeScript signatures hard to read.
- TypeScript typing. A generic
currythat gets its types exactly right needs advanced TypeScript features (tuple types, and conditional types that call themselves to peel off one parameter at a time). In practice use a small library or write the few curried signatures by hand.
What is a pure function, and what does immutability buy you? Take one small piece of code that mutates shared state and show how you would rewrite it as pure functions over immutable data. Where does that change help with testing, reasoning about the code, and running it concurrently, and where does it cost you?
Sample Answer
Direct answer
A pure function returns a result that depends only on its arguments and does nothing observable besides returning it: no reading or writing of outside variables, no I/O, no clock, no randomness. Call it twice with the same arguments and you get the same value. Immutability means a value is never changed after it is created; an "update" builds a new value and leaves the old one intact. Together they let you reason about a function by reading it alone, test it with plain inputs and outputs, and share its data across concurrent tasks without locks. The cost is allocation (copying: building a fresh value on every update) and some friction where the problem is naturally about changing state.
Rewrite: mutating shared state to pure functions
The impure version changes a shared cart object. The pure version takes the old cart and returns a new one.
// Impure: mutates a shared cart object
const cart = { items: [], total: 0 };
function addItemImpure(name, price) {
cart.items.push(name);
cart.total += price;
}
// Pure: same inputs always give the same output, nothing outside is touched
const addItem = (cart, name, price) => ({
items: [...cart.items, name],
total: cart.total + price,
});
// Testing
addItemImpure("pen", 2);
addItemImpure("pen", 2);
console.log("impure after 2 calls:", JSON.stringify(cart));
const empty = Object.freeze({ items: Object.freeze([]), total: 0 });
const c1 = addItem(empty, "pen", 2);
const c2 = addItem(c1, "book", 10);
console.log("pure c1:", JSON.stringify(c1));
console.log("pure c2:", JSON.stringify(c2));
console.log("empty untouched:", JSON.stringify(empty), "| same input twice equal:",
JSON.stringify(addItem(empty, "pen", 2)) === JSON.stringify(addItem(empty, "pen", 2)));
// Frozen input makes a hidden mutation fail loudly (push throws on a frozen array in any mode)
try { empty.items.push("x"); } catch (e) { console.log("frozen push ->", e.constructor.name); }
// Concurrency: read-modify-write across an await loses updates on shared state
let shared = 0;
async function bump() { const v = shared; await null; shared = v + 1; }
await Promise.all([bump(), bump(), bump()]);
console.log("shared mutable counter after 3 concurrent bumps:", shared);
// Immutable: every task computes from its own value, then results are combined
const bumpPure = async (v) => { await null; return v + 1; };
const results = await Promise.all([0, 0, 0].map(bumpPure));
console.log("pure results:", results, "sum of increments:", results.reduce((a, b) => a + b, 0));
// Cost: a copy per update is O(n)
let big = Object.freeze({ items: [], total: 0 });
let copies = 0;
for (let i = 0; i < 1000; i++) { copies += big.items.length; big = addItem(big, "x", 1); }
console.log("elements copied across 1000 appends:", copies);
Run as an ES module in a node:22 container (Node 22), it prints:
impure after 2 calls: {"items":["pen","pen"],"total":4}
pure c1: {"items":["pen"],"total":2}
pure c2: {"items":["pen","book"],"total":12}
empty untouched: {"items":[],"total":0} | same input twice equal: true
frozen push -> TypeError
shared mutable counter after 3 concurrent bumps: 1
pure results: [ 1, 1, 1 ] sum of increments: 3
elements copied across 1000 appends: 499500
Notes on the choices:
- The impure
addItemImpurehas no way to be called "again from a clean slate": the second call sees the first call's leftovers.addItem(empty, ...)can be called any number of times from the sameempty. Object.freezeis shallow (it freezes the object it is given, not objects nested inside it), so the example freezes theitemsarray too. Freezing is a safety net that turns an accidental mutation into aTypeError: methods such aspushthrow in any mode, while a plain assignment such ascart.total = 5throws only in strict mode (ES modules are always strict) and is silently ignored in sloppy-mode scripts. In TypeScript,readonlyandReadonlyArray<T>give the same protection at compile time at no runtime cost.
Where it helps
| Concern | Impure and shared | Pure and immutable |
|---|---|---|
| Testing | Arrange global state, call, inspect the global, reset it | Call with an input, compare the returned value. No setup, no teardown, no mocks for the logic itself |
| Reasoning | Any function that can reach cart might have changed it; you must read all of them | The result of addItem(c1, ...) is determined by what is written at the call site; c1 is still valid afterwards, which also makes undo, history and "previous vs next" comparison trivial |
| Concurrency | Two tasks interleave their read and write steps and an update is lost | Nothing is shared and writable, so there is nothing to lock |
The concurrency row is the output above. The three bump() calls each read shared as 0 before any of them writes, so the final value is 1, not 3. A data race is two threads touching the same memory at once with at least one writing, so the result depends on timing. JavaScript has no data race in that thread sense, but any read-modify-write that spans an await has the same lost-update shape. The pure bumpPure takes its input as an argument, returns a new value, and the caller combines the three results, so nothing can be overwritten. With real threads (Kotlin, Java, Scala) the argument is stronger: data that nobody can modify can be read from many threads without locks.
A second payoff is for UI code: React's useState and Redux reducers compare old and new state by reference (prev === next). A pure update that returns a new object when something changed, and the same object when nothing did, makes "did it change?" a one-pointer comparison.
Where it costs
- Copying. Each
addItemcopies the array: the last line of the output shows 499,500 element copies for 1,000 appends (0 + 1 + ... + 999), so building a list by repeated copy is quadratic. (Big-O notation describes how work grows with the size n of the input: O(n) means work proportional to n, so copying a 1,000-item array costs about 1,000 steps; O(log n) means work grows only with the number of times you can halve n, so about 10 steps for 1,000 items.) Persistent data structures are collections that keep every old version usable after an update by sharing the unchanged parts between the old and new version instead of copying them. They are balanced or tree-shaped, so one update copies one path from the root, about O(log n) rather than O(n). Haskell'sData.Mapis the standard example in Haskell, Immutable.js is a JavaScript library of such collections, and Immer is a library that lets you write ordinary-looking mutations on a draft copy and reuses every untouched branch of a plain JS object when it produces the new one. If you only remember one tool for a React/Redux app, Immer is the usual choice. In small, user-sized collections the copy is irrelevant; in a hot loop over millions of elements, a local mutation is the right call. - Allocation pressure. More short-lived objects means more work for the garbage collector (the runtime component that finds objects nothing references any more and frees their memory).
- Awkward fits. Genuinely stateful things (a canvas, a socket, a running counter shared by users) do not become pure by wishing; the pure part is the decision about what to do, and the effect is performed at the boundary.
- Local mutation is fine. A function that builds an array with
pushinside and returns it is still pure from the outside, because no caller can observe the mutation. Purity is a property of the interface, not of every line.
Same idea in Haskell
In Haskell values are immutable and functions are pure by default: addItem :: Cart -> String -> Int -> Cart cannot touch the outside world, and the type says so. Impurity must appear in the type (IO). JavaScript and TypeScript do not enforce any of this, so purity there is a discipline backed by freezing, readonly and code review.
You inherit a service where almost every business rule is tangled with database calls, HTTP requests and logging. How would you move it toward a pure core with effects at the edges? Walk through the incremental migration, how you would test the extracted logic, and when you would stop short of heavier abstractions.
Sample Answer
Direct answer
Move toward a functional core, imperative shell: a core of pure functions that take facts (already-loaded data, the current time, an id) and return decisions (a total, a list of messages to send), wrapped in a thin shell that loads the facts, calls the core, and performs the decisions. Do it incrementally and behind a safety net: first pin down what the code does today with characterization tests, then extract one business rule at a time into a pure function, then push the reads to the top of the handler and the writes to the bottom. Stop when the rules are pure and the shell is small; do not add effect frameworks until a concrete pain, such as a decision that depends on the result of an earlier effect, requires them.
Step by step
- Pin current behaviour (characterization tests). Before changing structure, run the legacy handler with fake collaborators (database, mailer, logger) over a representative set of inputs and record the outputs and the calls made. These are not "correct" tests; they are "same as before" tests. A seam is a place where behaviour can be swapped without editing the code around it; passing the collaborators (database, mailer, logger) in as parameters creates one, and it is a small change that does not alter behaviour. This passing-in is a form of dependency injection: a function receives the things it depends on instead of creating or importing them itself.
- Find the decisions. Read each handler and mark lines that only compute from data (discount rules, thresholds, which email to send) against lines that talk to the outside (
db.*,mailer.*,log, clock, random, environment). - Extract the pure core, one rule at a time. Copy a rule into a function whose parameters are everything it reads (
customer,order) and whose return value is everything it wants done (Decision). Leave the old code calling it. Ship after each extraction. - Return decisions instead of performing them. The core returns
notifications: [...]as data; it does not call the mailer. Time and randomness become parameters (now,newId) so the core stays repeatable. - Reshape the shell: read everything needed, call the core, write the results. Keep the order of effects the same as in the legacy code until the tests confirm equivalence; changing the order is a separate, deliberate change.
- Delete the old tangled version once both agree on the recorded cases and in production.
Worked example
type Order = { id: string; customerId: string; subtotalCents: number; coupon?: string };
type Customer = { id: string; tier: "basic" | "gold" };
type Db = { getCustomer(id: string): Customer; saveOrder(o: Order & { totalCents: number }): void };
type Mailer = { send(to: string, body: string): void };
// ---- Step 0: legacy handler, rules tangled with effects
function legacyCheckout(db: Db, mailer: Mailer, log: (m: string) => void, order: Order) {
log("checkout start " + order.id);
const c = db.getCustomer(order.customerId);
let total = order.subtotalCents;
if (c.tier === "gold") total = Math.round(total * 0.9);
if (order.coupon === "SAVE5") total = Math.max(0, total - 500);
db.saveOrder({ ...order, totalCents: total });
if (total > 10000) mailer.send(c.id, "big order " + order.id);
log("checkout done " + order.id);
return total;
}
// ---- Steps 2-4 of the list: pure core. Facts in, decision out. No I/O, no clock, no globals.
type Decision = { totalCents: number; notifications: { to: string; body: string }[] };
function decide(customer: Customer, order: Order): Decision {
let total = order.subtotalCents;
if (customer.tier === "gold") total = Math.round(total * 0.9);
if (order.coupon === "SAVE5") total = Math.max(0, total - 500);
return {
totalCents: total,
notifications: total > 10000 ? [{ to: customer.id, body: "big order " + order.id }] : [],
};
}
// ---- Step 5 of the list: thin imperative shell. Load, decide, act.
function checkout(db: Db, mailer: Mailer, log: (m: string) => void, order: Order) {
log("checkout start " + order.id);
const customer = db.getCustomer(order.customerId); // read
const d = decide(customer, order); // pure
db.saveOrder({ ...order, totalCents: d.totalCents }); // write
d.notifications.forEach((n) => mailer.send(n.to, n.body));
log("checkout done " + order.id);
return d.totalCents;
}
// ---- Characterization test: record what the OLD code does, demand the NEW code matches
function fakes() {
const saved: unknown[] = [], mails: string[] = [], logs: string[] = [];
const db: Db = {
getCustomer: (id) => ({ id, tier: id === "g" ? "gold" : "basic" }),
saveOrder: (o) => void saved.push(o),
};
return { db, mailer: { send: (to: string, b: string) => void mails.push(to + ":" + b) }, log: (m: string) => void logs.push(m), saved, mails, logs };
}
const cases: Order[] = [
{ id: "o1", customerId: "b", subtotalCents: 4000 },
{ id: "o2", customerId: "g", subtotalCents: 20000 },
{ id: "o3", customerId: "b", subtotalCents: 12000, coupon: "SAVE5" },
{ id: "o4", customerId: "g", subtotalCents: 300, coupon: "SAVE5" },
];
type Impl = typeof checkout;
function agree(impl: Impl, reference: Impl): boolean {
return cases.every((o) => {
const a = fakes(), b = fakes();
const ta = reference(a.db, a.mailer, a.log, o), tb = impl(b.db, b.mailer, b.log, o);
return ta === tb && JSON.stringify([a.saved, a.mails, a.logs]) === JSON.stringify([b.saved, b.mails, b.logs]);
});
}
console.log("refactor matches legacy:", agree(checkout, legacyCheckout));
// The harness can fail: a copy that nudges a gold customer's subtotal by one cent is caught
const broken: Impl = (db, m, l, o) => checkout(db, m, l, { ...o, subtotalCents: o.customerId === "g" ? o.subtotalCents + 1 : o.subtotalCents });
console.log("mutated refactor matches legacy:", agree(broken, legacyCheckout));
// Pure core tested with no fakes at all
const eq = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
console.log("gold 20000 ->", JSON.stringify(decide({ id: "g", tier: "gold" }, cases[1]!)));
console.log("coupon floors at 0:", decide({ id: "g", tier: "gold" }, cases[3]!).totalCents === 0);
console.log("pure and repeatable:", eq(decide({ id: "b", tier: "basic" }, cases[0]!), decide({ id: "b", tier: "basic" }, cases[0]!)));
Compiled with tsc 5.9.3 --strict --noUncheckedIndexedAccess --target es2022 and run in a node:22 container it prints:
refactor matches legacy: true
mutated refactor matches legacy: false
gold 20000 -> {"totalCents":18000,"notifications":[{"to":"g","body":"big order o2"}]}
coupon floors at 0: true
pure and repeatable: true
How to read the harness: fakes() builds a fresh set of recording stand-ins, whose saveOrder, send and log push into arrays instead of touching anything real. agree runs the reference and the candidate on each of the four cases, each with its own fresh fakes, and compares the returned total plus the three recorded arrays as JSON text; every is true only if all four cases match. Worked through, the four cases give totals 4000 (basic, no discount, no mail), 18000 (gold, 10 percent off 20000, mail sent), 11500 (basic, 12000 minus the 500 coupon, mail sent) and 0 (gold, 300 becomes 270, minus 500 clamped to 0, no mail). The ! in cases[1]! is a non-null assertion: the --noUncheckedIndexedAccess flag makes cases[1] typed as possibly undefined, and the ! tells the compiler the case exists.
What it demonstrates:
legacyCheckoutmixes the discount rules with reads, writes, email and logging.decideis the same rules with every effect removed;checkoutis the shell that performs them in the same order (log, read, write, send, log).- The characterization check
agree(checkout, legacyCheckout)compares the returned total, the saved orders, the mails and the log lines for four inputs and reportstrue. The harness can fail:brokenis the refactor with the gold customer's subtotal nudged by one cent, andagreereportsfalse, so a silent change to a rule is caught. - One limit of this harness:
saved,mailsandlogsare three separate arrays, so it compares the order within each kind of effect but not between kinds. A shell that sent the mail before saving the order would still printtrue. When the order between effects matters (step 5 above), push every call into one sharedcallsarray instead and compare that. - The pure core is tested without any fakes: 20,000 cents for a gold customer is 18,000 after the 10 percent discount, which is over 10,000 so one notification is produced; a 300-cent gold order with the 500-cent coupon floors at 0 (270 minus 500, clamped), an edge case the legacy code also had.
How the benefits show up
| Aspect | Before | After |
|---|---|---|
| Testing the rules | Needs a fake database, mailer and logger for every case | Plain inputs and outputs; hundreds of cases are cheap |
| Reasoning | A change to a discount might affect writes and emails | decide cannot write or send, so its blast radius (how much can break when it is wrong) is its return value |
| Reuse | Rules only run inside the request | The same decide can run in a batch job, a preview endpoint or a "what-if" API |
| Failure analysis | Partial failure is spread across the function | All writes and sends sit in one visible block, so you can see (and later fix) the "saved but mail failed" window |
When to stop short of heavier abstractions
Stop when the shell is a short, linear read, decide, act sequence and the core is covered by fast tests. Reach further only for a specific, observed need:
- A decision that depends on the result of an earlier effect (read, decide, read something else based on that, decide again). Keep the shell as a short loop or sequence of steps that calls the core several times, or have the core return a small data "plan" for the next step. This covers most real cases.
- Many handlers sharing the same effects, and you want to swap implementations (real, in-memory, recording). Pass a small interface of operations (the
DbandMailertypes above) as a parameter. That is plain dependency injection and is the practical default. - Effect-description abstractions (free monads, tagless final) are a heavier step toward the same goal of swapping interpreters. The idea in miniature: instead of calling
db.getCustomer(id), the program is built as data that says "get this customer, then continue with this function", and an interpreter walks that data.
type Customer = { id: string; tier: "basic" | "gold" };
type Program<A> =
| { tag: "done"; value: A }
| { tag: "getCustomer"; id: string; next: (c: Customer) => Program<A> }
| { tag: "send"; to: string; body: string; next: () => Program<A> };
const done = <A>(value: A): Program<A> => ({ tag: "done", value });
// A program is data: nothing is read or sent while it is being built.
const program: Program<number> = {
tag: "getCustomer",
id: "g",
next: (c) => {
const total = c.tier === "gold" ? 18000 : 20000;
return { tag: "send", to: c.id, body: "big order", next: () => done(total) };
},
};
// One interpreter: walks the data and records what it was asked to do.
function runForTest(p: Program<number>): { log: string[]; result: number } {
const log: string[] = [];
let cur: Program<number> = p;
while (cur.tag !== "done") {
if (cur.tag === "getCustomer") {
log.push("getCustomer " + cur.id);
cur = cur.next({ id: cur.id, tier: "gold" });
} else {
log.push("send " + cur.to + ": " + cur.body);
cur = cur.next();
}
}
return { log, result: cur.value };
}
console.log(JSON.stringify(runForTest(program)));
Compiled with tsc 5.9.3 --strict --target es2022 and run in a node:22 container it prints:
{"log":["getCustomer g","send g: big order"],"result":18000}
A real free monad adds a generic chaining operation so such programs are written in a normal sequential style instead of nested next functions; the walk-the-data interpreter is the same idea. In tagless final the program is instead written once against an interface and each interpreter implements it. Higher-kinded types are types that take another type constructor as a parameter (abstracting over "some container such as Promise or Array" rather than over Promise<number>); tagless final in its general form relies on them, which is why Haskell and Scala express it naturally and TypeScript does not. The trade-offs: interpreters are easy to write and many can coexist (a real one, a test one, a logging one), but building and walking program data adds overhead and indirection; type safety is strong in languages with higher-kinded types such as Haskell and Scala, but TypeScript has no direct way to write that abstraction, which weakens the types and makes the code harder to read; testability is excellent because the test interpreter is a few lines, though a plain fake Db gives most of the same value with far less machinery. For a typical TypeScript service, interface parameters are the proportionate choice.
Pitfalls
- Refactoring without characterization tests: a behaviour change hides inside a "cleanup".
- "Pure" functions that still read
Date.now(),process.envor a module-level cache. - Pulling all effects to the top when one read depends on another's result, creating a giant eager load; load lazily in the shell instead.
- Rewriting everything at once. Extract the highest-churn or highest-risk rule first and keep each step shippable.
- Changing effect order or transaction boundaries (save then mail) while moving code; keep the behaviour first, then improve it separately.
Without using the built-in map, implement map for a list or array by hand. Then explain how it composes with filter and reduce in a pipeline, and one downside of your hand-rolled version compared with the library one.
Sample Answer
Direct answer
map(arr, fn) returns a new array of the same length where each element is fn applied to the matching element of the input; the input is not changed. The hand-rolled version is a loop that allocates the result and fills it. map, filter and reduce compose into a pipeline: filter chooses which elements survive, map transforms them, reduce collapses them to one value, and each step takes the previous step's array as input. The hand-rolled version differs from the built-in in details such as sparse arrays, thisArg and the generic array-like behaviour, and every stage that returns an array (filter and map, but not a final reduce to a single value) builds an intermediate array.
Implementation, pipeline and the differences
// Naive: one loop, new array, calls fn on every index 0..length-1
function myMap(arr, fn) {
const out = new Array(arr.length);
for (let i = 0; i < arr.length; i++) out[i] = fn(arr[i], i, arr);
return out;
}
// Closer to the spec: skip holes, keep them in the result
function myMapSparse(arr, fn) {
const out = new Array(arr.length);
for (let i = 0; i < arr.length; i++) if (i in arr) out[i] = fn(arr[i], i, arr);
return out;
}
const myFilter = (arr, p) => { const out = []; for (let i = 0; i < arr.length; i++) if (p(arr[i], i, arr)) out.push(arr[i]); return out; };
const myReduce = (arr, f, init) => { let acc = init; for (let i = 0; i < arr.length; i++) acc = f(acc, arr[i], i, arr); return acc; };
console.log(myMap([1, 2, 3], (x) => x * 2));
console.log(myMap(["a", "b"], (s, i) => s + i));
const calls = [];
myMap([1, , 3], (x) => (calls.push(x), x)); // hand-rolled visits the hole
const callsB = [];
[1, , 3].map((x) => (callsB.push(x), x)); // built-in does not
console.log("naive visited:", calls, "| built-in visited:", callsB);
console.log("naive result :", myMap([1, , 3], (x) => x * 2), "| built-in:", [1, , 3].map((x) => x * 2));
const sp = myMapSparse([1, , 3], (x) => x * 2);
console.log("sparse-aware:", sp, "| has hole at 1:", !(1 in sp));
console.log("parseInt pitfall:", ["1", "2", "3"].map(parseInt), "fixed:", myMap(["1", "2", "3"], (s) => parseInt(s, 10)));
// Pipeline: sum of squares of the even numbers
const nums = [1, 2, 3, 4, 5, 6];
const result = myReduce(myMap(myFilter(nums, (n) => n % 2 === 0), (n) => n * n), (a, b) => a + b, 0);
console.log("pipeline (hand-rolled):", result, "| built-in:", nums.filter((n) => n % 2 === 0).map((n) => n * n).reduce((a, b) => a + b, 0));
// Each stage allocates a new array: count allocations
let allocs = 0;
const filt = (a, p) => (allocs++, myFilter(a, p));
const mp = (a, f) => (allocs++, myMap(a, f));
mp(filt(nums, (n) => n % 2 === 0), (n) => n * n);
console.log("intermediate arrays built by filter->map:", allocs);
// Single pass fused with reduce
console.log("single pass reduce:", myReduce(nums, (acc, n) => (n % 2 === 0 ? acc + n * n : acc), 0));
In the callbacks (x) => (calls.push(x), x), the comma operator evaluates its operands left to right and returns the last one: calls.push(x) records the element that was visited, and then x is returned as the mapped value, so the callback both logs and passes the value through.
Run in a node:22 container it prints:
[ 2, 4, 6 ]
[ 'a0', 'b1' ]
naive visited: [ 1, undefined, 3 ] | built-in visited: [ 1, 3 ]
naive result : [ 2, NaN, 6 ] | built-in: [ 2, <1 empty item>, 6 ]
sparse-aware: [ 2, <1 empty item>, 6 ] | has hole at 1: true
parseInt pitfall: [ 1, NaN, NaN ] fixed: [ 1, 2, 3 ]
pipeline (hand-rolled): 56 | built-in: 56
intermediate arrays built by filter->map: 2
single pass reduce: 56
Design choices
- The callback receives
(element, index, array), the same three arguments as the built-in, so callers can use the index. That is also the source of the classic bug on theparseInt pitfallline:["1","2","3"].map(parseInt)returns[1, NaN, NaN]becauseparseInttakes a second parameter (the radix, or number base) andmappasses the index there. MDN documents this exact behaviour; the fixes are(s) => parseInt(s, 10)orNumber. - The input is never written to, so
myMapis pure as long asfnis. Writing to a localoutarray is invisible to callers. - Complexity: O(n) time and O(n) extra space for the result. No edge case is special: an empty input gives an empty array, and an input of length 1 gives length 1.
Composing with filter and reduce
filter keeps elements for which a predicate returns true and reduce folds the remaining ones into one value, so "sum of squares of the even numbers" in the example reads left to right as filter (2, 4, 6), map (4, 16, 36), reduce (4 + 16 + 36 = 56). Every stage is a function from array to value, so stages can be swapped, reordered or tested separately. Order matters: filtering first means map squares 3 elements, not 6.
One downside of the hand-rolled version
The most visible one is sparse arrays (arrays with empty slots, as in [1, , 3]). The built-in map does not call the callback for an empty slot and keeps the hole in the result (MDN), but the naive loop visits index 1, hands undefined to the callback, and returns NaN there. The i in arr check in myMapSparse restores the built-in behaviour. Other differences: the built-in accepts an optional second argument, thisArg, which becomes this inside a regular (non-arrow) callback, and myMap has no such parameter. The built-in is also generic over array-like inputs, meaning objects that are not arrays but have a length and integer keys, such as { length: 3, 0: "a", 1: "b", 2: "c" }; Array.prototype.map.call(thatObject, fn) works on them (MDN), while myMap needs an array. In a Node 22 run, Array.prototype.map.call({ length: 3, 0: "a", 1: "b", 2: "c" }, (s) => s.toUpperCase()) gives [ 'A', 'B', 'C' ] and [1, 2].map(function (x) { return x * this.k; }, { k: 10 }) gives [ 10, 20 ].
A downside shared by the built-in and by any chain of them is the intermediate arrays: filter(...).map(...) builds two arrays (the "intermediate arrays" line shows 2 for the two-stage chain), where a single reduce pass or a plain loop builds none besides the result. For arrays of thousands of items this is irrelevant; for very large arrays or hot paths, fuse the stages in one loop, or use a lazy iterator pipeline, where each stage hands one element at a time to the next instead of building a whole array. With generator functions (functions that yield values on demand):
function* gFilter(it, p) { for (const x of it) if (p(x)) yield x; }
function* gMap(it, f) { for (const x of it) yield f(x); }
const nums = [1, 2, 3, 4, 5, 6];
const seen = [];
const lazy = gMap(
gFilter(nums, (n) => { seen.push("filter " + n); return n % 2 === 0; }),
(n) => { seen.push("map " + n); return n * n; });
let sum = 0;
for (const v of lazy) sum += v;
console.log(sum);
console.log(seen.join(", "));
Run in a node:22 container it prints:
56
filter 1, filter 2, map 2, filter 3, filter 4, map 4, filter 5, filter 6, map 6
The order shows the stages interleaving element by element (filter 2 is followed at once by map 2), and no intermediate array is ever built. Recursive versions ([f(head), ...map(tail)]) are an elegant alternative but cost a stack frame per element and copy on every spread, so a loop is the right tool in JavaScript.
Haskell contrast
Haskell's map f (x:xs) = f x : map f xs is the recursive form, and lazy evaluation means the result is produced element by element, so map and filter chains over a big list do not build full intermediate lists in memory when consumed incrementally.
That is every published Functional Programming question for Full-Stack Developer so far. Browse the other topics in this category, or practice this one interactively.