Compose functions with Lodash
Composite functions are built from smaller ones: _.flow chains functions left to right and _.curry lets you pass arguments one at a time.
How it works
- Chain functions.
_.flow([trim, lower, dashify])returns a new function that passes its input through each function in order. [1] - Curry a function.
_.curry(addTax)returns a function that the example calls both with two arguments at once and with one argument at a time. The docs list a curriedcurryNin the FP build too. [2] - Combine both. The curried
withVatis dropped into another_.flowpipeline that sums prices and rounds the result. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import _ from 'lodash';
// _.flow: left-to-right pipeline
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const dashify = (s) => s.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const slugify = _.flow([trim, lower, dashify]);
console.log('slugify:', slugify(' Hello Lodash World! '));
console.log('slugify:', slugify('Creating Composite Functions'));
// _.curry: supply arguments one at a time
const addTax = (rate, price) => price * (1 + rate);
const curried = _.curry(addTax);
const withVat = curried(0.2);
console.log('all at once:', curried(0.2, 50));
console.log('one by one: ', curried(0.2)(50));
console.log('withVat(10):', withVat(10));
// Both together
const sum = (list) => list.reduce((a, b) => a + b, 0);
const round2 = (n) => Math.round(n * 100) / 100;
const checkout = _.flow([sum, withVat, round2]);
console.log('cart [4.99, 12.5, 3]:', checkout([4.99, 12.5, 3]));
Add a fourth step to the slugify pipeline, such as cutting the result to 20 characters. Code written by AgentGid [1].
Add a fourth step to the slugify pipeline, such as cutting the result to 20 characters. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with lodash 4.18.1. Needs WebGL.
More Lodash examples
Default values with _.defaults Split arrays with _.partition Read nested values with _.at Iterate collections with Lodash
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.