实现一个 flowRight 的函数
分析flowRight的特点 :
- 会依次执行传入的函数, 并且顺序是从右往左 所以需要对参数 reverse
- 返回的结果是一个函数 , 并且这个函数需要对数据做处理,所以这个函数要传递进数据参数
- 传入的fn参数数量是不确定的 可以使用 args
- 每一项fn都需要执行,可以使用reduce
// 实现一个 flowRight
const myFlowRight = (...args)=>{
return function(value){
return args.reverse().reduce(function(result , fn){
return fn(result)
},value)
}
}
// reduce 对数组的每一项进行处理,并且返回处理的累计结果
// reduce 中 result 累计处理结果 ; fn 数组的每一项fn ; 第二个参数 value result的初始值
const first = arr => arr[0] ;
const reverse = arr => arr.reverse();
const toUpper = str => str.toUpperCase();
const fn = myFlowRight(toUpper , first, reverse)
console.log(fn(['one','two','three']));
// 使用箭头函数优化 myflowRight
const myFlowRightArrow = (...args) => {
return value => args.reverse().reduce((result , fn)=> fn(result),value)}
}
const fn2 = myFlowRightArrow(toUpper , first, reverse)
console.log(fn2(['one','two','three']));