Skip to content
jshacks.dev
Functions

How to Build a Mini Functional Library in 100 Lines

Build a mini functional library in about 100 lines of JavaScript with curry, compose, pipe, map, filter, reduce and prop, and use it on a data task. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Vite and Node.js logos.

Libraries such as Ramda and Lodash/fp are large, and most of what people use from them is a handful of ideas: every function takes its data last, every function can be partially applied and functions combine into pipelines. Those ideas fit in a hundred lines, and writing them once is the fastest way to understand what the libraries do. This post builds a small functional toolkit on Node.js 24: curry, pipe, compose, the list functions map, filter, reduce, sortBy and groupBy, the accessors prop and path, and a few helpers. Then it uses the toolkit on a realistic data task and compares the result with the plain method-chain version. Along the way it states what the toolkit leaves out, because a hundred lines is a teaching size, not a production size. For the single piece the whole design depends on, see implementing curry.

The foundation: curry

Everything else depends on curry. A curried function accepts its arguments one at a time or several at once, and returns a new function until it has enough. The data-last convention then lets you fix the configuration first, as in map(double), and supply the list later.

JavaScript
const curry = (fn) => {
  const curried = (...args) =>
    args.length >= fn.length ? fn(...args) : (...rest) => curried(...args, ...rest);

  return curried;
};

const add = curry((a, b, c) => a + b + c);

console.log(add(1)(2)(3), add(1, 2)(3), add(1)(2, 3), add(1, 2, 3));
Text
6 6 6 6

The function reads fn.length, the number of declared parameters, to know when it has enough arguments. That is also its limit: a function with default parameters or a rest parameter reports a shorter length, so curry does not suit those. Keep the curried functions in this library to fixed arities.

pipe and compose

pipe runs functions left to right and compose right to left. Both are a reduce over the list.

JavaScript
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const compose = (...fns) => pipe(...[...fns].reverse());

const inc = (n) => n + 1;
const double = (n) => n * 2;

console.log(pipe(inc, double)(5));
console.log(compose(inc, double)(5));
Text
12
11

pipe(inc, double) adds one and then doubles, (5 + 1) * 2 = 12. compose(inc, double) doubles first and then adds one, 5 * 2 + 1 = 11, matching the mathematical inc(double(5)). Most people find pipe easier to read because the code follows the order of execution, so the examples below use it.

The list functions, data last

Define each function with the data as the final parameter and wrap it in curry.

JavaScript
const map = curry((fn, list) => list.map((item) => fn(item)));
const filter = curry((pred, list) => list.filter((item) => pred(item)));
const reduce = curry((fn, init, list) => list.reduce(fn, init));
const sortBy = curry((fn, list) => [...list].sort((a, b) => (fn(a) < fn(b) ? -1 : fn(a) > fn(b) ? 1 : 0)));
const take = curry((n, list) => list.slice(0, n));

const groupBy = curry((fn, list) =>
  list.reduce((groups, item) => {
    const key = fn(item);
    (groups[key] ??= []).push(item);
    return groups;
  }, {}),
);

console.log(map(double)([1, 2, 3]));
console.log(filter((n) => n > 1)([1, 2, 3]));
console.log(take(2, sortBy((n) => -n, [3, 1, 2])));
console.log(groupBy((n) => (n % 2 ? "odd" : "even"), [1, 2, 3, 4]));
Text
[ 2, 4, 6 ]
[ 2, 3 ]
[ 3, 2 ]
{ odd: [ 1, 3 ], even: [ 2, 4 ] }

Two details in the implementation matter. map calls fn(item) with a single argument. Passing fn straight to list.map would hand it three arguments, the item, the index and the array, which breaks any curried function that has a different arity, the same trap as ["1", "2", "3"].map(parseInt). And sortBy copies the list first with [...list], because Array.prototype.sort sorts in place, and a library of pure functions must not change its input.

groupBy uses ??=, the logical nullish assignment, to create the array for a key on first use. The object it builds has the keys in the order they first appear.

Accessors

Data is usually objects, so prop and path turn property access into functions you can pass to map and sortBy.

JavaScript
const prop = curry((key, object) => object?.[key]);
const path = curry((keys, object) => keys.reduce((value, key) => value?.[key], object));

const user = { name: "Ada", address: { city: "London" } };

console.log(prop("name")(user));
console.log(path(["address", "city"], user));
console.log(path(["address", "zip"], user));
console.log(map(prop("name"), [{ name: "a" }, { name: "b" }]));
Text
Ada
London
undefined
[ 'a', 'b' ]

prop("name") is a function waiting for an object, which is exactly what map wants. The optional chain returns undefined for a missing path and never throws, which is the usual functional style: absence is a value.

Small helpers

Four more functions round out the kit.

JavaScript
const tap = curry((fn, value) => {
  fn(value);
  return value;
});

const not = (pred) => (value) => !pred(value);
const equals = curry((a, b) => a === b);
const uniq = (list) => [...new Set(list)];

const logged = pipe(map(double), tap((list) => console.log("after double:", list)), filter((n) => n > 2));

console.log(logged([1, 2, 3]));
console.log(filter(not(equals(2)), [1, 2, 3]));
console.log(uniq([1, 1, 2, 2, 3]));
Text
after double: [ 2, 4, 6 ]
[ 4, 6 ]
[ 1, 3 ]
[ 1, 2, 3 ]

tap runs a side effect and hands the value on, which makes it the debugging tool of a pipeline: insert it anywhere to print what flows through, then delete it, with no other change. The not helper negates a predicate, so filter(not(equals(2))) keeps everything except the twos.

Using it on a real task

Here is a small dataset and a question: for each team, what is the total salary of its active employees, listing teams from the largest total down?

JavaScript
const employees = [
  { name: "Ada", team: "core", salary: 120, active: true },
  { name: "Linus", team: "core", salary: 100, active: true },
  { name: "Grace", team: "tools", salary: 90, active: false },
  { name: "Brendan", team: "tools", salary: 80, active: true },
  { name: "Guido", team: "infra", salary: 70, active: true },
];

const sum = reduce((a, b) => a + b, 0);

const teamTotals = pipe(
  filter(prop("active")),
  groupBy(prop("team")),
  Object.entries,
  map(([team, members]) => ({ team, total: sum(map(prop("salary"), members)) })),
  sortBy((row) => -row.total),
);

console.log(teamTotals(employees));
Text
[
  { team: 'core', total: 220 },
  { team: 'tools', total: 80 },
  { team: 'infra', total: 70 }
]

Read the pipeline top to bottom: keep the active people, group them by team, turn the groups into entries, compute each team's total and sort by total descending. Grace is inactive, so tools counts only Brendan's 80. Each step is a small reusable function, and the pipeline itself is a value you can name, test and reuse on another dataset.

Compare it with the same task as a method chain.

JavaScript
const chain = Object.entries(
  employees
    .filter((e) => e.active)
    .reduce((groups, e) => {
      (groups[e.team] ??= []).push(e);
      return groups;
    }, {}),
)
  .map(([team, members]) => ({ team, total: members.reduce((s, e) => s + e.salary, 0) }))
  .sort((a, b) => b.total - a.total);

console.log(chain.length);
Text
3

Both give the same three rows. The method chain needs no library and is just as short, and it is what most JavaScript programmers read most easily. The toolkit shines when you reuse steps across pipelines, build them from configuration or pass them as arguments, and it is not worth the indirection when you write a chain once.

What the hundred lines leave out

The toolkit has no placeholder arguments, so you cannot skip a parameter when partially applying. It does not curry functions with default or rest parameters. It copies lists freely, which is fine at ordinary sizes, and it does no lazy evaluation, so each step creates an intermediate array. Errors inside a step show a stack trace through the curry wrapper, which is noisy. And there are no types. In TypeScript, a curried library needs generics for each arity, which is the main reason people reach for a typed library like Remeda or fp-ts, and the reason this toolkit is a learning exercise rather than something to ship.

If you do keep a small toolkit in a project, treat it as ordinary code: write tests, keep it free of surprises and add a function only when two places need it.

Growing the toolkit without losing control

The temptation after writing the first hundred lines is to keep adding functions. Resist it, and add one only when a real task needs it twice. Each addition costs tests, documentation and a name to remember, and a large homemade library becomes the thing the next person must learn before they can read your code.

When you do add, follow the same rules as the first ones. Data goes last. The function is pure and does not change its input. It takes one or a few arguments of fixed count so curry works. And it has a test that states the behavior on an empty list, because empty input is where small functional helpers most often disagree with each other: sum([]) should be zero, take(3, []) an empty list and groupBy an empty object.

A useful discipline is to write the data-first, method-chain version beside the pipeline for the first few uses. If the chain is clearer, keep the chain. The library earns its place by the pipelines that are built from configuration, reused across modules or composed from smaller pipelines, and not by looking functional.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("curry accepts arguments in any grouping", () => {
  const f = curry((a, b, c) => a * b + c);
  assert.equal(f(2)(3)(1), 7);
  assert.equal(f(2, 3)(1), 7);
});

test("list functions do not change their input", () => {
  const input = [3, 1, 2];
  sortBy((n) => n, input);
  assert.deepEqual(input, [3, 1, 2]);
});

test("pipe runs left to right and compose right to left", () => {
  assert.equal(pipe(inc, double)(1), 4);
  assert.equal(compose(inc, double)(1), 3);
});

test("the team pipeline sorts by total", () => {
  assert.deepEqual(map(prop("team"), teamTotals(employees)), ["core", "tools", "infra"]);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.