Iterate an array as a pair (current, next) in JavaScript

前端 未结 13 965
情话喂你
情话喂你 2020-12-09 09:06

In the question Iterate a list as pair (current, next) in Python, the OP is interested in iterating a Python list as a series of current, next pairs. I have th

13条回答
  •  执笔经年
    2020-12-09 09:55

    Here's my approach, using Array.prototype.shift:

    Array.prototype.pairwise = function (callback) {
        const copy = [].concat(this);
        let next, current;
    
        while (copy.length) {
            current = next ? next : copy.shift();
            next = copy.shift();
            callback(current, next);
        }
    };
    

    This can be invoked as follows:

    // output:
    1 2
    2 3
    3 4
    4 5
    5 6
    
    [1, 2, 3, 4, 5, 6].pairwise(function (current, next) {
        console.log(current, next);
    });
    

    So to break it down:

    while (this.length) {
    

    Array.prototype.shift directly mutates the array, so when no elements are left, length will obviously resolve to 0. This is a "falsy" value in JavaScript, so the loop will break.

    current = next ? next : this.shift();
    

    If next has been set previously, use this as the value of current. This allows for one iteration per item so that all elements can be compared against their adjacent successor.

    The rest is straightforward.

提交回复
热议问题