Pipe
Implement pipe(...fns). It returns a function that passes all its arguments to the first function, then each result to the next function, from left to right. With no functions it returns its first argument. The tests name the steps: inc adds 1, double multiplies by 2, sum adds two numbers, label puts a v in front.
Start from
function pipe(...fns) {
// Return a function that runs fns from left to right.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
The first function is special: it receives every argument. The others receive one value.
Hint 2
reduce over the rest of the functions, starting from the first function's result.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function pipe(...fns) {
return (...args) =>
fns.length
? fns.slice(1).reduce((value, fn) => fn(value), fns[0](...args))
: args[0];
}What an interviewer looks for
Function composition shows up in middleware, selectors and data transforms. The direction (pipe goes left to right, compose right to left) is the usual trap.