Open serendipityApe opened 2 years ago
题目 what is Composition? create a pipe() 例子
题目 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) } }
答案
/** * @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) } }
创建一个pipe()函数,它能将多个函数聚合成一个新的函数
案例,我们有下面几个函数
通过pipe()你能得到下面的结果