Our solution for the pipe() function will be fairly simple. For every function call in the argument array funcs, it will return a new function.

This one will perform a reduce operation, which will call the sequence of functions and give them their arguments. Each argument of reduce() has to return the values that the next function requires.

From the perspective of the next function, the parameter that should be passed into it should come from the previous call of reduce(). In reduce(), result is the return value and func is the current value of the funcs array.

JAVASCRIPT
1return funcs.reduce((result, func) => {
2  return func(result);
3}, arg);

Since the reduce() method also requires an initialValue, we will provide it with the current arg, because if not provided, the first element of an array will be used as initialValue and this will be a function and it will be omitted from execution. Then, the second element of an array will be used as the first func of the loop.

So, the solution would look like this:

JAVASCRIPT
1function pipe(funcs) {
2  return function (arg) {
3    return funcs.reduce((result, func) => {
4      return func(result);
5    }, arg);
6  }
7}

So, in terms of some of the previous examples, the execution would go something like this:

JAVASCRIPT
1pipe([
2  times(2),
3  subtract(3),
4  divide(4)
5])
  1. The reduce method gets times(2) as a parameter, and performs its action (multiplies by 2)
  2. Then the result returned gets passed to the subtract(3) function, and 3 is subtracted from the result
  3. Finally the operation divide(4) gets performed over the current result, and it gets divided by 4