The iterator

An iterator is a special type of object that has some proprietary interface designed for the iterative process. All iterator objects have a next() method that returns a result object on each call. The result object has two properties: one is value, which indicates the next value to be returned; The other is done, which is a Boolean value that returns true if there is no more data to return. Iterators also hold an internal pointer to the position of the value in the current collection, and each call to next() returns the next available value

If next() is called after the last value has been returned, the object returned with the done property true and the value property containing the iterator’s final return value. This return value is not part of the data set. It is similar to the return value of a function and is the last method to pass information to the caller during the function call. Return undefined if there is no relevant data

Let’s create an iterator using ES5 syntax

function createIterator(items) { var i = 0;

return {

next: function() {

var done = (i >= items.length);

var value = ! done ? items[i++] : undefined;

return {

done: done,

value: value

};

}

};

}

var iterator = createIterator([1, 2, 3]);

console.log(iterator.next()); // “{ value: 1, done: false }”

console.log(iterator.next()); // “{ value: 2, done: false }”

console.log(iterator.next()); // “{ value: 3, done: false }”

console.log(iterator.next()); // “{ value: undefined, done: true }”

// All subsequent calls

console.log(iterator.next()); // “{ value: undefined, done: true }”

Generators (which generate iterators and yield the value returned)

A generator is a function that returns an iterator, denoted by an asterisk (*) after the function keyword. The new keyword yield is used in the function. The asterisk can be next to the function keyword, or a space can be added in between

Function *createIterator() {

yield 1;

yield 2;

yield 3;

}

// A generator can be called like a normal function, but returns an iterator

let iterator = createIterator();

console.log(iterator.next().value); / / 1

console.log(iterator.next().value); / / 2

console.log(iterator.next().value); / / 3