reduce方法を実現する


reduce方法を実現する
Array.prototype._reduce = function (fn, initial) {
    //                undefined  null               
    let hasInitial = initial != undefined
    //          0      1
    let index = hasInitial ? 0 : 1
    let acc = this[0]
    let cur
    //              acc
    if (hasInitial) {
        acc = initial
    }
    //                  :                      index
    for (var i = index; i < this.length; i++) {
        cur = this[i]
        //           acc
        acc = fn(acc, cur, i)
    }
    return acc
}
 reduceRight方法
Array.prototype._reduceRight = function (fn, initial) {
    let hasInitial = initial != undefined
    let index = hasInitial ? 0 : 1
    let start = this.length - 1
    //            
    let acc = this[start]
    let cur
    if (hasInitial) {
        acc = initial
    }
    //                         
    for (var i = this.length - 1 - index; i >= 0; i--) {
        cur = this[i]
        acc = fn(acc, cur, i)
    }
    return acc
}