serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

合并函数 pipe() #13

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目 what is Composition? create a pipe()

例子

创建一个pipe()函数,它能将多个函数聚合成一个新的函数

案例,我们有下面几个函数

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

通过pipe()你能得到下面的结果

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

答案

/**
* @param {Array<(arg: any) => any>} funcs 
* @return {(arg: any) => any}
*/
function pipe(funcs) {
//arg为新函数的参数
return function(arg){
return funcs.reduce((result,item) => {
return item.call(this,result);
},arg)
}
}