# what is Composition? create a pipe()

70 阅读1分钟

Today,let's solve a problem with "what is Composition? create a pipe()". link: bigfrontend.dev/problem/wha…

What is Composition? It is actually not that difficult to understand,see @dan_abramov's explanation.

Here you are asked to create a pipe() function, which chains multiple functions together to create a new function.

Suppose we have some simple functions like this:

const times = (y) =>  (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) =>  (x) => x - y
const divide = (y) => (x) => x / y

Your pipe() would be used to generate new functions

pipe([
  times(2),
  times(3)
])  
// x * 2 * 3

pipe([
  times(2),
  plus(3),
  times(4)
]) 
// (x * 2 + 3) * 4

pipe([
  times(2),
  subtract(3),
  divide(4)
]) 
// (x * 2 - 3) / 4

According to the meaning of the question,firstly,we can create a pipe function that takes a parameter and returns a function.

function pipe(funcs){
    return function(arg){}
}

The "arg" is the variable that we want to handle,and the "funcs" is an array of manipulation functions.

So,we should return the result of the "arg" processed sequentially by the function in "funcs".

We can use the for of loop to iterate through the "funcs" array,and then let the "arg" equal to the result of each manipulation function.

Finally,we just need to return the arg.

function pipe(funcs){
    return function(arg){
        for (let func of funcs) {
            arg = func(arg)
        }
        return arg
    }
}

Okay,and if you are familiar with the ES6,you can use the reduce API to make the code more elegant.

Like this:

function pipe(funcs){
    return function(arg){
        return funcs.reduce((result, func) => func(result), arg)
    }
}

Anyway,i hope it helps for you.

See you next time.

Bye Bye.