Sub topic 17
Functional Style in Real Codebases: Trade-offs and Libraries
This chapter assumes you know the earlier tools: pure functions, immutable updates, map/filter/reduce, pipe, currying, and Maybe. The question now is how much of that style to use in a real project, and which libraries help.
Where Functional Style Pays Off
Functional code works best where data flows through steps:
- Data transformation. Reshaping API responses or computing reports reads well as a pipeline.
- State updates. UI frameworks such as React and Redux compare references to detect changes, so immutable updates are required there.
- Testing. A pure function needs no mocks. You pass inputs and check the output.
- Concurrency of reasoning. When nothing is mutated, you can read a function on its own without tracking who else touches the data.
Where It Costs You
| Cost | Cause | Mitigation |
|---|---|---|
| Extra allocations | Each `map`/`filter` builds a new array; each spread copies an object | Combine steps in hot loops, or use generators for long sequences |
| Stack limits | Engines rarely perform tail-call optimization | Use `reduce` or loops for deep or large inputs |
| Readability for the team | Point-free chains and heavy currying are unfamiliar to many developers | Name intermediate functions; keep chains short |
| Debugging | Stack traces through `pipe` show anonymous wrappers | Insert a `tap` step that logs, or use named functions |
| False safety | `Object.freeze` and `const` are shallow | Use `structuredClone`, Immer, or careful nested spreads |
The shallow-freeze trap catches many people:
const config = Object.freeze({ retries: 3, hosts: ['a.example'] });
config.retries = 10; // silently ignored (throws in strict mode)
config.hosts.push('b.example'); // works: the inner array is not frozen
console.log(config.retries, config.hosts); // 3 [ 'a.example', 'b.example' ]When performance matters, measure first. A single reduce that does several steps at once avoids building intermediate arrays:
const orders = Array.from({ length: 5 }, (_, i) => ({ total: i * 10, paid: i % 2 === 0 }));
// Readable: three passes, two intermediate arrays
const a = orders.filter((o) => o.paid).map((o) => o.total).reduce((s, t) => s + t, 0);
// One pass, no intermediate arrays
const b = orders.reduce((s, o) => (o.paid ? s + o.total : s), 0);
console.log(a, b); // 60 60Start with the readable version. Switch to the single pass only if profiling shows the chain is a bottleneck.
Libraries
| Library | What it gives you | Good fit |
|---|---|---|
| Ramda | Auto-curried, data-last utilities (`pipe`, `prop`, `sum`) | Pipeline-heavy code, point-free style |
| lodash/fp | Lodash functions with curried, data-last arguments | Teams already using Lodash |
| Immer | Write "mutating" code on a draft and get an immutable copy | Nested state updates, Redux Toolkit |
| fp-ts / Effect | Typed `Option`, `Either`, and effect types for TypeScript | Large TypeScript codebases with strict error handling |
Install with npm install ramda immer and run as an ES module (.mjs file):
import * as R from 'ramda';
import { produce } from 'immer';
const paidRevenue = R.pipe(
R.filter(R.prop('paid')),
R.map(R.prop('total')),
R.sum
);
console.log(paidRevenue([{ total: 40, paid: true }, { total: 15, paid: false }])); // 40
const state = { todos: [{ text: 'write', done: false }] };
const next = produce(state, (draft) => {
draft.todos[0].done = true;
});
console.log(state.todos[0].done, next.todos[0].done); // false trueA Decision Guide
A practical default is a functional core with an imperative shell. Keep business logic pure and immutable. Put I/O, logging, and DOM work in a thin outer layer.
Exercise
A teammate freezes a settings object with Object.freeze and assumes nested arrays are now safe from changes. What goes wrong, and name two fixes.
Show answer
Object.freeze is shallow, so nested arrays and objects can still be mutated. Fixes: copy nested data before changing it (nested spread or structuredClone), freeze recursively with a deep-freeze helper, or manage updates with Immer, which produces new copies and freezes them automatically in development.
Exercise
A filter-map-reduce chain over 2 million records shows up in a profiler as slow. What change would you try first, and what do you give up?
Show answer
Merge the steps into a single reduce (or a plain for loop) so that no intermediate arrays are built. You give up some readability and the ability to reuse each step separately.