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

前端 未结 13 968
情话喂你
情话喂你 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:57

    Another solution using iterables and generator functions:

    function * pairwise (iterable) {
        const iterator = iterable[Symbol.iterator]()
        let current = iterator.next()
        let next = iterator.next()
        while (!current.done) {
            yield [current.value, next.value]
            current = next
            next = iterator.next()
        }
    }
    
    console.log(...pairwise([]))
    console.log(...pairwise(['apple']))
    console.log(...pairwise(['apple', 'orange', 'kiwi', 'banana']))
    console.log(...pairwise(new Set(['apple', 'orange', 'kiwi', 'banana'])))

    Advantages:

    • Works on all iterables, not only arrays (eg. Sets).
    • Does not create any intermediate or temporary array.
    • Lazy evaluated, works efficiently on very large iterables.

提交回复
热议问题