Implementation of reduce method

Time:2021-2-6

Implementation of reduce method

Array.prototype._reduce = function (fn, initial) {
    //If there is an initial value, note that the initial value is passed to undefined or null, and there is no initial value, but null means there is a value
    let hasInitial = initial != undefined
    //If there is an initial value, the loop starts at 0, otherwise it is 1
    let index = hasInitial ? 0 : 1
    let acc = this[0]
    let cur
    //If there is an initial value, it is assigned to ACC directly
    if (hasInitial) {
        acc = initial
    }
    //The loop executes the callback function once and passes in three parameters: the cumulative value of each execution, the item being traversed, and the index being traversed
    for (var i = index; i < this.length; i++) {
        cur = this[i]
        //Here we assign the return value to acc
        acc = fn(acc, cur, i)
    }
    return acc
}

Reducereight method

Array.prototype._reduceRight = function (fn, initial) {
    let hasInitial = initial != undefined
    let index = hasInitial ? 0 : 1
    let start = this.length - 1
    //But the default here is to start from the right
    let acc = this[start]
    let cur
    if (hasInitial) {
        acc = initial
    }
    //The loop also starts from the right, and if there is an initial value, it starts from the penultimate
    for (var i = this.length - 1 - index; i >= 0; i--) {
        cur = this[i]
        acc = fn(acc, cur, i)
    }
    return acc
}

Recommended Today

Modern Enterprise Architecture Framework – Application Architecture

Modern Enterprise Architecture Framework:https://mp.weixin.qq.com/s/SlrEu0_t0slijrNZ6DP4Ng Business Architecture:https://mp.weixin.qq.com/s/zQCjiHuxFvAg5QiOAuLAcQ 4. Application Architecture The core concern of application architecture is which applications carry the business requirements, how they interact with users, how and how they interact, and what data they access or change. The design of the application architecture is mainly based on the application (Application) design as the […]