媒介
关于reduce,能够之前关于他的用法只是用于累加,但实在他的真正用处适用于作为一个高阶函数,用于完成函数式编程里的 compose
compose的个人明白
建立一个函数,起码吸收两个参数,一个函数数组,一个初始参数,顺次实行函数数组,下一个函数的第一个参数是上一个的效果,初始参数是第一个函数的第一个参数。
lodash完成
reduce
<!-- 吸收4个参数,第一个是要实行的数组,第二个是回调函数,第三个是初始参数,第4个是是不是跳过第一个回调并拿第一个参数当作下一个回调的参数 -->
function reduce(collection, iteratee, accumulator) {
const func = Array.isArray(collection) ? arrayReduce : baseReduce
const initAccum = arguments.length < 3
<!-- baseEach是当collection不是数组时的完成 -->
return func(collection, iteratee, accumulator, initAccum, baseEach)
}
arrayReduce
function arrayReduce(array, iteratee, accumulator, initAccum) {
let index = -1
const length = array == null ? 0 : array.length
if (initAccum && length) {
accumulator = array[++index]
}
// 当initAccum为true时,从下标为1的最先运转
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array)
}
return accumulator
}
baseReduce
<!-- 当collection是对象时的完成 -->
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, (value, index, collection) => {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection)
})
return accumulator
}
baseEach
<!-- 对collection是差别范例的处置惩罚 -->
function baseEach(collection, iteratee) {
if (collection == null) {
return collection
}
<!-- 推断是不是是非常规的Array,比方arguments -->
if (!isArrayLike(collection)) {
<!-- 这里的详细就是跑了个for -->
return baseForOwn(collection, iteratee)
}
const length = collection.length
const iterable = Object(collection)
let index = -1
while (++index < length) {
<!-- 这里的详细就是跑了个for,initAccum为true时第一次跳过 -->
if (iteratee(iterable[index], index, iterable) === false) {
break
}
}
return collection
}