DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 26

The task is to create a pipe function that chains multiple functions together to create a new function. Each function in the chain should take one argument and return a value.

The boilerplate code

function pipes(funcs) {
}
Enter fullscreen mode Exit fullscreen mode

The pipe function takes an array of functions. It returns a new function that takes an initial value

return function(arg) {

}
Enter fullscreen mode Exit fullscreen mode

In the returned function, the reduce function is used to call each function in the array accordingly. The result of each function is passed to the next function.

return funcs.reduce((acc, fn) => fn(acc), arg)
Enter fullscreen mode Exit fullscreen mode

The final result is returned after all the functions have been called. The final code is:

function pipe(funcs) {
    // your code here
    return function(arg) {
        return funcs.reduce((acc, fn) => fn(acc), arg)
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)