Implement curry, compose and pipe.
curry
Turns f(a, b, c) into a function that can be called as f(a)(b)(c), f(a, b)(c) or f(a)(b, c). Collect arguments until there are at least fn.length of them, then call the original.
compose and pipe
Combine functions into one:
pipe(f, g, h)(x)=h(g(f(x))): left to right, reads like a pipeline.compose(f, g, h)(x)=f(g(h(x))): right to left, as in mathematics and Redux'scomposefor middleware. Both are areduceover the function list.
Where they show up
Partial application for event handlers and selectors, data transformation pipelines, Redux middleware and enhancers, higher-order components (compose(withRouter, withTheme)(Component)).
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...more) => curried.apply(this, [...args, ...more]);
};
}
const pipe = (...fns) => input => fns.reduce((acc, fn) => fn(acc), input);
const compose = (...fns) => input => fns.reduceRight((acc, fn) => fn(acc), input);
// Demo
const volume = curry((l, w, h) => l * w * h);
assert.equal(volume(2)(3)(4), 24);
assert.equal(volume(2, 3)(4), 24);
assert.equal(volume(2)(3, 4), 24);
const trim = s => s.trim();
const lower = s => s.toLowerCase();
const slug = s => s.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const toSlug = pipe(trim, lower, slug);
assert.equal(toSlug(' Hello React & Vue! '), 'hello-react-vue');
assert.equal(compose(slug, lower, trim)(' Hello React & Vue! '), 'hello-react-vue');
// Async pipeline: each step may return a promise
const pipeAsync = (...fns) => input => fns.reduce((p, fn) => p.then(fn), Promise.resolve(input));
assert.equal(await pipeAsync(x => x + 1, async x => x * 10)(1), 20);
// Curried helpers read well in array methods
const prop = curry((key, obj) => obj[key]);
assert.deepEqual([{ id: 1 }, { id: 2 }].map(prop('id')), [1, 2]);
console.log('curry, pipe and compose work');Example
Infinite currying is a popular variant: sum(1)(2)(3)() returns 6, where calling with no argument ends the chain.
function sum(a) {
return function next(b) {
return b === undefined ? a : sum(a + b);
};
}
assert.equal(sum(1)(2)(3)(), 6);
assert.equal(sum(5)(), 5);A variant without the final () overrides valueOf or toString on the returned function so it converts to the total, but that is a trick, not a pattern for real code.
Follow-up questions interviewers ask
Try answering each one before you open it.
Why does curry use fn.length and when does that break?
fn.length is the number of declared parameters before the first one with a default value or a rest parameter. For (a, b = 1) => ... or (...args) => ... it is 1 or 0, so curry calls too early. Accept an explicit arity: curry(fn, arity = fn.length).