Generators offer a simple, clean way to write custom iterators.
Using ES6 classes, and iterator could be constructed like this:
class RangeIterator {
constructor(start, stop) {
this.value = start;
this.stop = stop;
}
[Symbol.iterator]() { return this; }
next() {
var value = this.value;
if (value < this.stop) {
this.value++;
return {done: false, value: value};
} else {
return {done: true, value: undefined};
}
}
}
// Return a new iterator that counts up from 'start' to 'stop'.
function range(start, stop) {
return new RangeIterator(start, stop);
}
Which can be radically simplified by using a generator function instead:
function* range(start, stop) {
for (var i = start; i < stop; i++)
yield i;
}
This can furthermore be used to refactor complicated loops, by using generator functions to handle the parts that generate the data. Then, one can simply use it in a for-of loop: for (let data of myNewGenerator(args))
Generators offer a simple, clean way to write custom iterators.
Using ES6 classes, and iterator could be constructed like this:
Which can be radically simplified by using a generator function instead:
This can furthermore be used to refactor complicated loops, by using generator functions to handle the parts that generate the data. Then, one can simply use it in a for-of loop:
for (let data of myNewGenerator(args))
More information: https://hacks.mozilla.org/2015/05/es6-in-depth-generators/