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.
How does property-based testing differ from example-based testing? Write a property for 'reversing a list twice gives back the original' in a tool you know (QuickCheck, fast-check, Hypothesis), explain how inputs are generated and how a failing case is shrunk, and name one limitation.
Sample Answer
Direct answer
An example-based test checks the cases you thought of: reverse([1,2,3]) should be [3,2,1]. A property-based test states a rule that must hold for every input of a kind, and a tool generates many random inputs to try to break it. The example checks one input; the property is tried against many generated inputs (100 random inputs per run by default in fast-check, configurable with numRuns). When a generated input fails, the tool shrinks it: it repeatedly tries smaller variants that still fail, and reports the smallest one, so you debug [0,0] rather than a 40-element array of large numbers.
The property, run
Using fast-check (a JavaScript/TypeScript library; QuickCheck in Haskell and Hypothesis in Python work the same way). The file also contains a deliberately buggy reverseBuggy (it also drops adjacent duplicates) so you can watch a failure and a shrink:
import fc from "fast-check";
const reverse = (xs) => xs.reduceRight((acc, x) => [...acc, x], []);
// A plausible-looking bug: "reverse" that also drops adjacent duplicates.
const reverseBuggy = (xs) => reverse(xs).filter((x, i, arr) => i === 0 || x !== arr[i - 1]);
const reverseTwice = (rev, elem = fc.integer()) => fc.property(fc.array(elem), (xs) => {
const twice = rev(rev(xs));
return twice.length === xs.length && twice.every((x, i) => x === xs[i]);
});
// 1. the correct implementation passes 100 random cases (the default)
fc.assert(reverseTwice(reverse));
console.log("reverse: property held");
// 2. the buggy one fails; fc.check returns the report instead of throwing
const wide = fc.check(reverseTwice(reverseBuggy), { seed: 42 });
console.log("buggy, any 32-bit integers, seed 42, failed:", wide.failed);
// a bug about equal neighbours needs inputs where neighbours are often equal
const report = fc.check(reverseTwice(reverseBuggy, fc.integer({ min: 0, max: 3 })), { seed: 42 });
console.log("buggy, integers 0..3, seed 42, failed:", report.failed);
console.log("shrunk counterexample:", JSON.stringify(report.counterexample[0]));
// 3. one example-based test of the same buggy function passes
const example = reverseBuggy(reverseBuggy([1, 2, 3]));
console.log("example [1,2,3] ->", JSON.stringify(example));
// 4. what generated inputs look like
console.log("sample inputs:", JSON.stringify(fc.sample(fc.array(fc.integer()), { seed: 42, numRuns: 4 })));
// 5. limitation: a property only checks what you thought to state
console.log("identity passes too:", fc.check(reverseTwice((xs) => xs)).failed === false);
// 6. how often does each generator catch the bug? Same property, seeds 1 to 200
let wideHits = 0, narrowHits = 0;
for (let seed = 1; seed <= 200; seed++) {
if (fc.check(reverseTwice(reverseBuggy), { seed }).failed) wideHits++;
if (fc.check(reverseTwice(reverseBuggy, fc.integer({ min: 0, max: 3 })), { seed }).failed) narrowHits++;
}
console.log("seeds that catch the bug, any integers:", wideHits, "of 200 | integers 0..3:", narrowHits, "of 200");
Run in a node:22 container with npm i fast-check@3 first (installed version 3.23.2), it prints (save the file as prop.mjs, run node prop.mjs):
reverse: property held
buggy, any 32-bit integers, seed 42, failed: false
buggy, integers 0..3, seed 42, failed: true
shrunk counterexample: [0,0]
example [1,2,3] -> [1,2,3]
sample inputs: [[],[-576819238,-872008521,1594409417,-1285903064,1752520020,-864546692,-246443128,440518484],[755983738,-1493108906,1433989693,-1755610965,-94247611,2103360753],[-20,1789811753]]
identity passes too: true
seeds that catch the bug, any integers: 16 of 200 | integers 0..3: 200 of 200
How inputs are generated
fc.array(fc.integer()) is an arbitrary: an object that knows how to produce random values of a type, driven by a seeded pseudo-random generator (a formula that produces numbers that look random but are fully determined by its starting number, the seed, so the same seed gives the same sequence). Arbitraries compose like the functions they wrap, so fc.array(elem) builds arrays out of any element arbitrary. Per run the tool draws the array length, then each element. The sample inputs line shows four generated arrays for seed 42. With a fixed seed the same inputs come back every time, which is how a failure found in CI is replayed on your laptop (fast-check prints the seed with the failure).
How a failing case is shrunk
Every arbitrary also knows how to propose simpler versions of a value it made: integers move toward 0, arrays drop elements and simplify the ones that remain. After a failure the runner tries those candidates, keeps any that still fail, and repeats until no simpler candidate fails. That is why the report above ends with [0,0]: a two-element array of equal values is the smallest input on which reverseBuggy breaks the rule, and the bug's cause (adjacent equal values) is visible in the answer itself.
One limitation: the property only sees what the generator produces
The run above shows it twice. With default 32-bit integers and seed 42, reverseBuggy passed: equal neighbours are rare when values are spread over 2^32 = 4,294,967,296 possibilities. The scan in step 6 shows it is rare but not impossible, because fast-check's integer generator is not uniform and favours small values: with the default integers 16 of 200 seeds (8%) caught the bug within 100 runs, so a green run on one seed says little. With elements limited to 0..3 there are just 4 values, a given pair of neighbours matches one time in 4, and all 200 seeds caught it (counts measured with fast-check 3.23.2; the exact numbers can change between versions). Restricting the elements made equal neighbours common and the bug was found at once. Generators must be shaped to the bug class you worry about. The related limits are in the last line: x => x also satisfies "reversing twice gives back the original", so a property can be true of a wrong implementation, and passing never proves correctness, only that nothing failed in the samples drawn. In practice you pair a few example tests (the cases you know matter) with properties. Three kinds of property recur. A round trip: converting and converting back returns the start, such as parse(print(x)) equal to x. Idempotence: doing the operation twice gives the same result as doing it once, such as sort(sort(xs)) equal to sort(xs), or trimming an already trimmed string. An invariant: something that stays true of the output whatever the input, such as "output is sorted and has the same length".
You must transform a multi-gigabyte file of line-delimited records, parsing each, dropping invalid ones and writing JSON out, in constant memory. Design the pipeline using lazy or streaming constructs (generators, iterators, lazy sequences or a streaming library). Why does it avoid the memory blowup of reading everything first, and what breaks that property?
Sample Answer
Direct answer
Build the pipeline as a chain of generators (functions that produce values one at a time, on demand, instead of building a whole list). Each stage pulls one item from the stage before it, does its work, and yields one item to the stage after it. Nothing asks for "all the records", so memory stays small and bounded at any moment (a chunk of the file, the lines readline has read ahead, the record being processed and the output buffer), whatever the file size. The final stage is a writable stream (an output sink with a bounded buffer); Node's stream.pipeline connects the stages and pauses the reader whenever the sink is full (back-pressure: a slow consumer slows the producer instead of letting data pile up between them).
Design: read, parse, filter, serialise, write
Four files make up the demo, all in one directory: three scripts and a shell runner. make-data.mjs creates the input:
// 1,000,000 lines "id,name,amount"; every 10th line is invalid (amount is not a number)
import { createWriteStream } from "node:fs";
const out = createWriteStream("records.csv");
for (let i = 1; i <= 1_000_000; i++) {
out.write(`${i},user-${i},${i % 10 === 0 ? "n/a" : (i % 977) + ".25"}\n`);
}
out.end();
stream.mjs is the streaming pipeline. Two Node pieces are used: readline (a built-in module that reads a stream one line at a time) and yield* (inside a generator, hand over each value of another iterable one by one). An async function* is an async generator: like a generator, but it may await and is consumed with for await ... of, which waits for each item in turn.
import { createReadStream, createWriteStream } from "node:fs";
import { createInterface } from "node:readline";
import { pipeline } from "node:stream/promises";
// parse: one line -> record, or null when invalid
const parseLine = (line) => {
const [id, name, amount] = line.split(",");
const n = Number(amount);
return Number.isFinite(n) && id && name ? { id: Number(id), name, amount: n } : null;
};
// each stage is a generator: it pulls one item, yields one item, and keeps no list of past items
async function* lines(path) {
yield* createInterface({ input: createReadStream(path), crlfDelay: Infinity });
}
async function* parsed(source) {
for await (const line of source) {
const rec = parseLine(line);
if (rec) yield rec; // invalid lines are dropped here
}
}
async function* toJsonLines(source) {
for await (const rec of source) yield JSON.stringify(rec) + "\n";
}
let peakRss = 0;
const timer = setInterval(() => (peakRss = Math.max(peakRss, process.memoryUsage().rss)), 20);
await pipeline(
async function* () { yield* toJsonLines(parsed(lines("records.csv"))); },
createWriteStream("out.jsonl")
);
clearInterval(timer);
console.log("streaming: done, peak RSS under 150 MB:", peakRss < 150 * 1024 * 1024);
The read-everything-first version of the same job, for comparison, is readall.mjs:
import { readFileSync, writeFileSync } from "node:fs";
const parseLine = (line) => {
const [id, name, amount] = line.split(",");
const n = Number(amount);
return Number.isFinite(n) && id && name ? { id: Number(id), name, amount: n } : null;
};
const records = readFileSync("records.csv", "utf8").split("\n").map(parseLine).filter(Boolean);
writeFileSync("out-all.json", JSON.stringify(records));
console.log("read-all: done,", records.length, "records");
run.sh generates a 1,000,000-line input, then runs both jobs with the JavaScript heap (the memory the engine manages for objects and strings) capped at 32 MB (--max-old-space-size=32). The pipeline's check uses RSS (resident set size: all physical memory the process holds, which also counts the Node runtime, compiled code and stream buffers that live outside the capped heap). That is why RSS is compared with its own generous 150 MB ceiling rather than with 32 MB: the cap limits the heap only, and the ceiling confirms the process as a whole stays small. The 25 MB test file stands in for a multi-gigabyte one: what matters is the ratio of input size to memory available, and a 32 MB cap against a 25 MB file reproduces the same failure at a size that runs in seconds.
run.sh:
node make-data.mjs
sleep 1
echo "input bytes: $(stat -c %s records.csv)"
node --max-old-space-size=32 stream.mjs; echo "streaming exit code: $?"
echo "output lines: $(wc -l < out.jsonl)"
node --max-old-space-size=32 readall.mjs > readall.log 2>&1; echo "read-all exit code: $?"
grep -m1 -o "heap out of memory" readall.log
Run in a node:22 container (Linux) with sh run.sh, it prints:
input bytes: 25376416
streaming: done, peak RSS under 150 MB: true
streaming exit code: 0
output lines: 900000
read-all exit code: 134
heap out of memory
The streaming job writes all 900,000 valid records (every tenth line has n/a as its amount and is dropped) under the same cap that makes the read-all job abort with heap out of memory (exit code 134 is 128 plus signal 6, SIGABRT, the signal a process sends itself when it aborts). The RSS line is informational (it prints true or false and does not set the exit code); the evidence is the exit codes. A variant of stream.mjs whose toJsonLines first pushes every record into an array aborts the same way, with exit code 134 and heap out of memory, under the same cap.
Why it avoids the blowup
readFileSync(...).split("\n").map(...) holds the file as one string, then as an array of line strings, then as an array of objects, all alive at once, so memory grows linearly with the input and the process dies when it passes the limit. The generator chain is pull-based: for await asks the previous stage for the next item only when this stage is ready, so records flow through the stages one at a time and become garbage once written. One stage reads ahead: the readline async iterator queues lines and pauses its input when the queue reaches 1,024 lines (highWaterMark: 1024 in the Node 22 source). That is a fixed bound, so memory stays constant, but it is a queue of lines, not literally one line. The stream's buffer is bounded by its highWaterMark; Node's documentation describes that as a threshold at which the stream stops asking for more data, not a hard memory limit.
What breaks the property
- Collecting anywhere.
Array.from(stage), spreading,toArray, orawait Promise.all(...)over the stream materialises everything (builds the full result in memory at once). So do operations that need all the data: global sort, group-by, and de-duplication with aSet(it grows with the number of distinct keys). Fix by an external sort (sort pieces small enough to fit in memory, write each sorted piece to disk, then merge the pieces by reading them in parallel), or by moving that step to a database. - Ignoring back-pressure. If you write with a manual loop and never wait when
write()returnsfalse, Node's documentation says it buffers every chunk until memory runs out and then aborts.pipeline(orawait once(stream, "drain")in a loop, wheredrainis the event the stream emits when its buffer has emptied and it is safe to write again) is what keeps the producer paced. - Unbounded concurrency. Starting one async task per line (
lines.map(async ...)collected in an array) holds every in-flight task in memory. Cap the concurrency (a small worker pool or a batch of N) if a stage does I/O. - One enormous record. The chain is constant-memory per record; a single multi-hundred-megabyte line is buffered whole by the line reader.
- Keeping evidence. Pushing every rejected line into an error array re-creates the problem. Count the invalid lines and keep only a bounded sample.
Failure behaviour
pipeline destroys every stream in the chain when any stage throws and rejects its promise, so a bad file does not leave handles open. A malformed line is handled in parseLine (returns null, the stage drops it), so one bad record does not stop the job. The output is only complete if the promise resolves, so write to a temporary file and rename it on success if downstream readers must never see a partial file.
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.
A function can fail. Compare returning an optional value, returning a result that carries an error, and throwing. When would you reach for a Result/Either type over Option/Maybe, and how do callers combine several such calls without nested null or error checks? Show a small example in a language you know.
Sample Answer
Direct answer
Use an optional (Option / Maybe, or T | undefined in TypeScript) when the only thing the caller needs to know is "there is a value or there isn't", such as a lookup by key. Use a result (Result / Either) when failure has a reason the caller can act on or display (which field, what code). Use throwing for failures the caller is not expected to handle locally: programmer errors, broken invariants, and unexpected conditions that should unwind to a boundary such as a request handler. The functional styles put the failure in the return type, so the compiler makes callers deal with it, and they compose through a function usually called andThen / flatMap / bind that runs the next step only if the previous one succeeded.
The three styles side by side
Vocabulary used in the code: <T, U, E> are generics, placeholders for types filled in at each use (T the success value going in, U the success value coming out, E the error type). Result is a discriminated union: a union whose members share a field (ok) with a different literal value in each, so checking r.ok narrows the type, meaning the compiler then knows which member r is and only allows r.value after r.ok is true. never is the type with no values; Result<T, never> therefore says "a success whose error side can never happen", which is why ok(5) can be used wherever a Result<number, ParseError> is expected.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
// andThen: run the next step only if the previous one succeeded
const andThen = <T, U, E>(r: Result<T, E>, f: (t: T) => Result<U, E>): Result<U, E> => (r.ok ? f(r.value) : r);
const mapR = <T, U, E>(r: Result<T, E>, f: (t: T) => U): Result<U, E> => (r.ok ? ok(f(r.value)) : r);
type ParseError = { code: "not_a_number" | "out_of_range" | "missing"; input: string };
const parseAge = (s: string): Result<number, ParseError> => {
const n = Number(s);
return s.trim() === "" || Number.isNaN(n) ? err({ code: "not_a_number", input: s }) : ok(n);
};
const checkRange = (n: number): Result<number, ParseError> =>
n >= 0 && n <= 120 ? ok(n) : err({ code: "out_of_range", input: String(n) });
// Option-style: absence only, no reason
const findUser = (db: Record<string, { age: string }>, id: string): { age: string } | undefined => db[id];
const db = { u1: { age: "34" }, u2: { age: "abc" }, u3: { age: "200" } };
// Throwing version: caller must know to try/catch, and the type does not say it can fail
function ageOrThrow(s: string): number {
const r = andThen(parseAge(s), checkRange);
if (!r.ok) throw new Error(r.error.code);
return r.value;
}
// Result chain: no nested if checks
function ageOfUser(id: string): Result<number, ParseError> {
const u = findUser(db, id);
if (u === undefined) return err({ code: "missing", input: id });
return andThen(parseAge(u.age), checkRange);
}
for (const id of ["u1", "u2", "u3", "u9"]) console.log(id, JSON.stringify(ageOfUser(id)));
console.log("mapR:", JSON.stringify(mapR(ageOfUser("u1"), (n) => n + 1)));
// Option-style chain with optional chaining and ??
const city: string = ({ a: { addr: { city: "Oslo" } } } as Record<string, any>)["a"]?.addr?.city ?? "unknown";
const none: string = ({ } as Record<string, any>)["b"]?.addr?.city ?? "unknown";
console.log(city, none);
// Throwing: the failure path is invisible to the type
try { ageOrThrow("200"); } catch (e) { console.log("caught:", (e as Error).message); }
// Collect all errors instead of stopping at the first
const validateAll = (ids: string[]) => {
const rs = ids.map(ageOfUser);
const errors = rs.flatMap((r) => (r.ok ? [] : [r.error.code]));
return errors.length ? err(errors) : ok(rs.flatMap((r) => (r.ok ? [r.value] : [])));
};
console.log(JSON.stringify(validateAll(["u1", "u2", "u3"])));
console.log(JSON.stringify(validateAll(["u1"])));
Compiled with tsc 5.9.3 --strict --target es2022 and run in a node:22 container it prints:
u1 {"ok":true,"value":34}
u2 {"ok":false,"error":{"code":"not_a_number","input":"abc"}}
u3 {"ok":false,"error":{"code":"out_of_range","input":"200"}}
u9 {"ok":false,"error":{"code":"missing","input":"u9"}}
mapR: {"ok":true,"value":35}
Oslo unknown
caught: out_of_range
{"ok":false,"error":["not_a_number","out_of_range"]}
{"ok":true,"value":[34]}
Comparing them
| Optional | Result / Either | Throw | |
|---|---|---|---|
| Carries the reason | No | Yes (error field) | Yes (an error object, but its type is not part of the function's signature) |
| Visible in the signature | Yes | Yes | No: ageOrThrow(s): number looks infallible |
| Caller must handle it | Yes, the compiler checks | Yes, you must read ok before value | No; forgetting is silent until it fires |
| Composition | ?., ??, map/flatMap | andThen, mapR | try/catch blocks that jump out of the flow |
| Best for | Lookups, optional fields, "not found" | Validation, parsing, calls with distinct failure modes | Bugs, impossible states, failures to propagate to a boundary |
When Result over Option: as soon as two different failures need different handling or different messages. In the output, u2, u3 and u9 all fail, but one is bad text, one is out of range and one is missing, and a UI shows different messages for each. An Option would give three identical None values and the reason would be lost.
Combining several calls without nested checks
The nested-null version is if (a) { if (b) { if (c) ... } }. With a result type, ageOfUser is a straight line: look up the user, andThen(parseAge(...), checkRange). The first ok: false skips the rest and is returned unchanged, so the failure arrives at the caller with no extra code. mapR transforms the success value without touching a failure (the mapR: ... 35 line). The difference between the two: mapR takes a function that returns a plain value (n => n + 1), while andThen takes a function that itself returns a Result (such as checkRange, which can fail). Using mapR with checkRange would wrap a result in a result, Result<Result<number, ParseError>, ParseError>, and callers would have to check twice; andThen flattens that into one layer. For Option-like data, optional chaining ?. (stop and give undefined as soon as something on the path is null or undefined) and nullish coalescing ?? (use the right side when the left is null or undefined) do the same job for property paths: Oslo is found, and the missing path returns the "unknown" default. In the example the object literal is cast with as Record<string, any> only so TypeScript allows indexing it by an arbitrary string key; the cast is not part of the technique.
When you want all the problems instead of the first one (form validation), you do not chain; you run each check independently and collect the failures, as validateAll does for u1, u2 and u3: the output lists not_a_number and out_of_range. This is the usual reason a validation layer is not a plain andThen chain: the chain is short-circuiting by design (it stops at the first failure and skips every later step).
Haskell contrast
Reading the Haskell below: Either String Int is a value that is either Left a String (the failure, by convention) or Right an Int (the success). readMaybe s returns Just n when s parses and Nothing otherwise, and maybe d f m means "if m is Nothing use d, otherwise apply f to what is inside", so maybe (Left ...) Right (readMaybe s) turns Nothing into a Left message and Just n into Right n. ++ joins strings, show turns a number into text, and the | lines in checkRange are guards, tried top to bottom.
import Text.Read (readMaybe)
parseAge :: String -> Either String Int
parseAge s = maybe (Left ("not a number: " ++ s)) Right (readMaybe s)
checkRange :: Int -> Either String Int
checkRange n | n >= 0 && n <= 120 = Right n
| otherwise = Left ("out of range: " ++ show n)
main :: IO ()
main = do
print (parseAge "34" >>= checkRange)
print (parseAge "200" >>= checkRange)
print (parseAge "abc" >>= checkRange)
print (do { a <- parseAge "30"; b <- parseAge "40"; checkRange (a + b) })
Right 34
Left "out of range: 200"
Left "not a number: abc"
Right 70
(runghc in a haskell:9.6-slim container.) >>= (read "bind") is andThen for Either String: given a result and a function that returns the next result, it runs the function only on Right and passes a Left through unchanged. A type with such a chaining operation is what Haskell calls a monad; in practice that means it "supports andThen". In the do block, a <- parseAge "30" means "run parseAge; if it is Right, call its value a and continue; if Left, stop with that Left", so the block is the same chain written as sequential statements; the first Left stops it. Rust's Result with ?, Kotlin's Result, and Scala's Either are the same idea.
Trade-offs and pitfalls
- Throwing is not wrong: for an invariant violation or a failure that every caller would just re-throw, a result type adds ceremony with no benefit. Mix the styles deliberately: wrap I/O boundaries that throw (
fetch,JSON.parse) into results at the edge, and let genuine bugs throw. - A result type is only as good as its error type.
Result<T, string>loses the structure that the UI needs; use a discriminated union of error codes as above. - In plain JavaScript there is no compiler to make callers check
ok, so the benefit comes from TypeScript (or from team convention). Withstrict, readingr.valuewithout narrowing onr.okis a compile error. - Annotate an Option-style return explicitly. Indexing a
Record<string, T>is typed as always present unlessnoUncheckedIndexedAccessis on, so without the| undefinedonfindUserthe callfindUser(db, "u9").agecompiles under--strictand fails at run time; with it, the compiler reportsObject is possibly 'undefined'. - Do not swallow errors by converting every failure to
undefined; that turns a Result problem back into an Option and loses the reason.
Copying a large map on every update to keep it immutable would be far too slow, yet libraries like Immutable.js and Clojure's collections do it cheaply. Explain how a persistent map can give you a new version while sharing most of its memory with the old one, what that costs per operation, and whether you would build one yourself or adopt a library in a production app.
Sample Answer
Direct answer
A persistent data structure keeps every old version valid after an update. For a map the standard way is a tree, not a flat table: an update copies only the nodes on the path from the root to the changed entry and points all other branches at nodes the old version already owns. This is structural sharing. With a wide tree (32 children per node), a map of 100,000 entries is only a handful of levels deep, so an update copies about a handful of small nodes instead of 100,000 entries. The usual design is a hash array mapped trie (HAMT). A trie is a tree where each step down is chosen by the next piece of the key, the way you look a word up letter by letter. A hash is a fixed-size number computed from the key, so the pieces can be bits of that number. In a HAMT you hash the key, use 5 bits of the hash per level to pick one of 32 slots, and store a bitmap (one bit per possible slot, set when the slot is in use) so empty slots take no space. Clojure's documentation states the cost model: collections make their performance guarantees for persistent use, and hash-map access takes log32 N hops. Here log32 N means "how many times you can divide N by 32 before reaching 1": 32 x 32 x 32 = 32,768 and 32 to the 4th is 1,048,576, so even a million entries need only about 4 levels when the tree is balanced.
Start here: one hash, one bitmap, one array index
A 32-bit hash is cut into 5-bit pieces, and each piece is a number from 0 to 31. Level 1 uses the lowest 5 bits, level 2 the next 5, and so on. For the key "key500" the hash function used below (FNV-1a, a small fast hash that turns a string into a 32-bit number) gives:
hash of key500: 01110111100101010100100000010011
shift 0: piece 19 = 10011
shift 5: piece 0 = 00000
shift 10: piece 18 = 10010
The expression (hash >>> shift) & 31 produces each piece: >>> shift slides the bits right by shift places and drops the low ones, and & 31 keeps only the lowest 5 bits, because 31 is 11111 in binary. So at the root, key500 goes to slot 19; one level down, slot 0; and so on.
A node does not hold 32 array cells. It holds a short array of only the children that exist, plus a 32-bit bitmap saying which slots those are. Suppose a node's children sit in slots 3, 9 and 20. Its bitmap has bits 3, 9 and 20 set, and its slots array has exactly 3 items, ordered by slot number. To find the array position for a piece, count how many set bits sit below it:
bitmap: 100000000001000001000 (bits 3, 9, 20 set)
piece 9: bit 1<<9 is present. Bits below it: 000000000000000001000 (one bit) -> array index 1
piece 20: bit 1<<20 is present. Bits below it: 000000000001000001000 (two bits) -> array index 2
piece 5: bit 1<<5 is absent -> key not in this node (a miss, or a free slot for an insert)
In code: 1 << piece builds a number with only that bit set (bit); bit - 1 turns it into a mask with every lower bit set; bitmap & (bit - 1) keeps only the occupied slots below the piece; and popcount (population count: how many bits are 1) turns that into the array index. That is the whole trick: a 32-way node costs only as many array cells as it has children. This script (node:22, saved as pieces.js, run with node pieces.js) computes the same pieces and indexes:
const fnv1a = (s) => { let h = 0x811c9dc5; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193); return h >>> 0; };
const h = fnv1a("key500");
console.log("hash of key500:", h.toString(2).padStart(32, "0"));
for (const shift of [0, 5, 10]) { const p = (h >>> shift) & 31; console.log(`shift ${shift}: piece ${p} = ${p.toString(2).padStart(5, "0")}`); }
const bitmap = (1<<3)|(1<<9)|(1<<20);
console.log("bitmap:", bitmap.toString(2));
const pop = (x)=>{let n=0;for(x|=0;x!==0;x&=x-1)n++;return n};
for (const piece of [9,20,5]) { const bit = 1<<piece; console.log(piece, (bitmap&bit)!==0, (bitmap&(bit-1)).toString(2).padStart(21,"0"), pop(bitmap&(bit-1))); }
It prints:
hash of key500: 01110111100101010100100000010011
shift 0: piece 19 = 10011
shift 5: piece 0 = 00000
shift 10: piece 18 = 10010
bitmap: 100000000001000001000
9 true 000000000000000001000 1
20 true 000000000001000001000 2
5 false 000000000000000001000 1
Each row after bitmap: is the piece, whether its bit is set, the bits below it, and the resulting array index; for the absent piece 5 the index 1 is only where an insert would go.
Two more words used below. A collision is two different keys with the same full 32-bit hash; the leaf then keeps a small list (a collision bucket) and compares the real keys. A leaf is the bottom node holding the key and value.
A working sketch (get, set, collisions, sharing measured)
type Entry<V> = readonly [string, V];
type Leaf<V> = { readonly kind: "leaf"; readonly hash: number; readonly entries: readonly Entry<V>[] };
type Branch<V> = { readonly kind: "node"; readonly bitmap: number; readonly slots: readonly (Branch<V> | Leaf<V>)[] };
type Slot<V> = Branch<V> | Leaf<V>;
let allocated = 0; // counts every node or leaf created, so the demo can report the copying cost
const mkLeaf = <V>(hash: number, entries: readonly Entry<V>[]): Leaf<V> => (allocated++, { kind: "leaf", hash, entries });
const mkNode = <V>(bitmap: number, slots: readonly Slot<V>[]): Branch<V> => (allocated++, { kind: "node", bitmap, slots });
const popcount = (x: number): number => {
let n = 0;
for (x |= 0; x !== 0; x &= x - 1) n++;
return n;
};
const fnv1a = (s: string): number => {
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193);
return h >>> 0;
};
const replaceAt = <T>(a: readonly T[], i: number, x: T): T[] => { const c = a.slice(); c[i] = x; return c; };
const insertAt = <T>(a: readonly T[], i: number, x: T): T[] => [...a.slice(0, i), x, ...a.slice(i)];
// Two leaves with different hashes meet in one slot: push both down until their 5-bit pieces differ.
function split<V>(a: Leaf<V>, b: Leaf<V>, shift: number): Branch<V> {
const fa = (a.hash >>> shift) & 31, fb = (b.hash >>> shift) & 31;
if (fa === fb) return mkNode(1 << fa, [split(a, b, shift + 5)]);
return mkNode((1 << fa) | (1 << fb), fa < fb ? [a, b] : [b, a]);
}
function setIn<V>(n: Branch<V>, h: number, k: string, v: V, shift: number): Branch<V> {
const bit = 1 << ((h >>> shift) & 31);
const i = popcount(n.bitmap & (bit - 1));
if ((n.bitmap & bit) === 0) return mkNode(n.bitmap | bit, insertAt(n.slots, i, mkLeaf(h, [[k, v]])));
const s = n.slots[i];
if (s.kind === "node") return mkNode(n.bitmap, replaceAt(n.slots, i, setIn(s, h, k, v, shift + 5)));
if (s.hash !== h) return mkNode(n.bitmap, replaceAt(n.slots, i, split(s, mkLeaf(h, [[k, v]]), shift + 5)));
const j = s.entries.findIndex(([ek]) => ek === k); // same full hash: keep a small collision bucket
const entries = j < 0 ? [...s.entries, [k, v] as Entry<V>] : replaceAt(s.entries, j, [k, v] as Entry<V>);
return mkNode(n.bitmap, replaceAt(n.slots, i, mkLeaf(h, entries)));
}
class PMap<V> {
static readonly empty = new PMap<never>(mkNode(0, []), fnv1a);
private constructor(readonly root: Branch<V>, private readonly hashFn: (k: string) => number) {}
withHash(hashFn: (k: string) => number): PMap<V> { return new PMap(this.root, hashFn); }
set(k: string, v: V): PMap<V> { return new PMap(setIn(this.root, this.hashFn(k), k, v, 0), this.hashFn); }
get(k: string): V | undefined {
const h = this.hashFn(k);
let n: Slot<V> = this.root;
for (let shift = 0; n.kind === "node"; shift += 5) {
const bit = 1 << ((h >>> shift) & 31);
if ((n.bitmap & bit) === 0) return undefined;
n = n.slots[popcount(n.bitmap & (bit - 1))];
}
return n.entries.find(([ek]) => ek === k)?.[1];
}
}
// ---------- 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));
};
const nodesOf = <V>(s: Slot<V>, out: Set<Slot<V>> = new Set()): Set<Slot<V>> => {
out.add(s);
if (s.kind === "node") s.slots.forEach((c) => nodesOf(c, out));
return out;
};
const depthOf = <V>(s: Slot<V>): number => (s.kind === "leaf" ? 0 : 1 + Math.max(0, ...s.slots.map(depthOf)));
const N = 100_000;
let v1 = PMap.empty as PMap<number>;
for (let i = 0; i < N; i++) v1 = v1.set("key" + i, i);
eq("get existing", [v1.get("key0"), v1.get("key99999")], [0, 99999]);
eq("get missing", v1.get("nope"), undefined);
const before = allocated;
const v2 = v1.set("key500", -1);
const created = allocated - before;
eq("new version sees the update", v2.get("key500"), -1);
eq("old version is unchanged", v1.get("key500"), 500);
const all1 = nodesOf(v1.root), all2 = nodesOf(v2.root);
const shared = [...all2].filter((s) => all1.has(s)).length;
console.log(`entries: ${N}, nodes+leaves in v1: ${all1.size}, max depth: ${depthOf(v1.root)}`);
console.log(`one set(): created ${created}, v2 has ${all2.size}, shared with v1: ${shared}`);
console.log(`copying the whole map would touch ${N} entries; this touched ${created} nodes/leaves`);
eq("created + shared == size of v2", created + shared, all2.size);
eq("an update copies only one path", created <= depthOf(v1.root) + 1, true);
eq("new version shares over 99% of the old nodes", shared > all1.size * 0.99, true);
// Collision bucket: a deliberately bad hash makes different keys share a full hash.
const bad = (PMap.empty as PMap<number>).withHash((k) => k.length);
const c = bad.set("ab", 1).set("cd", 2).set("ef", 3).set("ab", 9);
eq("collisions keep every key", [c.get("ab"), c.get("cd"), c.get("ef")], [9, 2, 3]);
eq("collision overwrite leaves old version", bad.set("ab", 1).set("cd", 2).get("ab"), 1);
if (failures > 0) throw new Error(failures + " checks failed");
How the code maps to the idea above: popcount counts set bits by repeatedly clearing the lowest one (x &= x - 1). fnv1a is the hash. setIn is the update: it computes bit and the array position i exactly as in the Start here section; if the bit is absent it builds a new node with the leaf inserted at position i (insertAt), and if the slot holds a deeper node it recurses one level (shift + 5) and builds a new node pointing at the recursive result (replaceAt copies the slots array with one entry swapped). Every branch returns a fresh node through mkNode, which is why only the path from the root down is copied while all sibling slots are reused as they are. split handles two different keys landing in the same slot: if their next pieces are equal (say both 7) it creates a one-slot node and recurses to the following piece; when the pieces differ (say 2 and 30) it creates a node with bits 2 and 30 set and the two leaves ordered by piece. get walks down the same way with no copying. eq just prints pass or FAIL for each check.
Compiled and run (TypeScript 5, node:22 container):
npx -y -p typescript@5 tsc --strict --target es2022 --module commonjs --outDir out hamt.ts
node out/hamt.js
pass get existing: [0,99999]
pass get missing: undefined
pass new version sees the update: -1
pass old version is unchanged: 500
entries: 100000, nodes+leaves in v1: 131465, max depth: 6
one set(): created 5, v2 has 131465, shared with v1: 131460
copying the whole map would touch 100000 entries; this touched 5 nodes/leaves
pass created + shared == size of v2: 131465
pass an update copies only one path: true
pass new version shares over 99% of the old nodes: true
pass collisions keep every key: [9,2,3]
pass collision overwrite leaves old version: 1
Reading the numbers: the map has 100,000 entries stored in 131,465 nodes and leaves, with at most 6 branch levels on any path (random hashes cluster, so the worst path is deeper than the average). One set created 5 new objects (the branches on the path plus the new leaf) and the new version points at 131,460 objects the old version also owns. created + shared == size of v2 is checked in code, but that equation holds even for a map that copies everything, so two further checks carry the sharing claim: created is at most the depth plus one, and shared is more than 99% of the old node count. A variant of setIn that deep-copies every untouched sibling passes the first four checks and fails both of these. Copying the whole map would have touched 100,000 entries. The old version still answers 500 for key500, so it is unchanged.
What it costs per operation
- get / has: O(log32 n) hops. At 100,000 entries that is a few array lookups, but each hop is a pointer chase to a separate object, so expect a larger constant factor than the built-in
Map, which is a single hash-table probe. Measure on your own data before deciding it matters. - set / delete: O(log32 n) new nodes, each copying its slots array (up to 32 entries), so about (depth x up to 32 slots) work and allocation per update, independent of the map size apart from the logarithm. The five new objects above are the measured case.
- merge: no better than inserting each entry of the smaller map, about m x O(log32 n) for m entries, unless the library has a structural shortcut.
- Memory: an old version costs only the nodes unique to it. Once nothing references it, the garbage collector reclaims those nodes, and the shared part stays alive because the new version uses it.
- Contrast: Haskell's
Data.Mapis a size-balanced binary tree, soinsertandlookupare O(log n) with base 2, which means more levels than the 32-way trie but the same idea of copying only a path.
Build or adopt
Adopt. Writing a HAMT correctly means getting hash collisions, deletion with node compaction (shrinking or merging nodes that become nearly empty after a removal), equality, iteration order and performance tuning right, and the sketch above omits deletion, iteration and transient (batched) updates on purpose. A transient is a temporary mutable copy of the map used for a burst of updates and then frozen back into a persistent version, which avoids allocating a new path for every one of 10,000 consecutive inserts. My recommendation by situation: for application state made of plain objects and arrays (React, Redux), use Immer, which lets you write ordinary mutations on a draft and produces a new state where, per its documentation, unchanged parts of the tree are shared in memory with the old state; for large keyed collections updated one key at a time, with many retained versions (undo history, time travel), use a persistent-collections library such as Immutable.js; for small objects, spread copies ({...obj, k: v}) are simpler and fast enough, so measure first. Build your own only as a learning exercise or if you have a measured need no library meets.
Unlock Full Question Bank
Get access to all 6 Functional Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.