reducer 对Array.prototype.reduce的解析
demo来自这里:关于Array.reducer developer.mozilla.org/zh-CN/docs/…
const array1 = [1, 2, 3, 4]
// (参数1是前一次的返回结果,参数2数组遍历时当前参数)
const reducer = (accumulator, currentValue) => accumulator + currentValue
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer))
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5))
// expected output: 15
思考题
function f1(arg) {
console.log('f1', arg)
return arg
}
function f2(arg) {
console.log('f2', arg)
return arg
}
function f3(arg) {
console.log('f3', arg)
return arg
}
// 想要的效果
f1(f2(f3('abc')))
// f3
// f2
// f1
// 用以下调用实现,目的实现compose方法
const fake = compose(f1,f2,f3)('abc')
以下是实现
const comreducer = (a, b) => (...args) => a(b(...args))
function compose(...args) {
if (args.length === 0) {
return null
}
return args.reduce(comreducer)
}