/Getting Started

ES6 (Javascript) : Iterators

Iterators:

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator’s return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should simply continue to return {done: true}. The most common iterator in Javascript is the Array iterator, which simply returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true.

Arrays must be allocated in their entirety, but iterators are consumed only as neccessary and thus can express sequences of unlimited size, such as the range of integers between 0 and Infinity. Here is an example which can do just that. It allows creation of a simple range iterator which defines a sequence of integers from start (inclusive) to end (exclusive) spaced step apart. Its final return value is the size of the sequence it created.

Example:

function makeRangeIterator(start = 0, end = Infinity, step = 1) {
    let nextIndex = start;
    let loopCount = 0;
    let returned = false;
    const rangeIterator = {
        next: function() {
            var result;
            if (nextIndex <= end) {
                result = {
                    value: nextIndex,
                    done: false
                }
                nextIndex += step;
                loopCount++;
            } else /* final value already returned */ {
                result = {
                    value: loopCount,
                    done: true
                }
            }
            return result;
        }
    };
    return rangeIterator;
}
let it = makeRangeIterator(1, 10, 2);
let result = it.next();
while (!result.done) {
    console.log(result.value); // 1 3 5 7 9
    result = it.next();
}
console.log(“Iterated over sequence of size:, result.value);
Ankitkamboj

Ankitkamboj

The professional learning platform

Read More