Iterators and Generators
Manual Iterators
Build a small object with a next method.
Manual Iterators
manual_iterator.js
const limit = 3;
let current = 1;
const values = [];
let value = null;
let done = false;
const iterator = {
next() {
if (current <= limit) {
const value = current;
current = current + 1;
return { value, done: false };
}
return { value: null, done: true };
},
};
({ value, done } = iterator.next());
while (!done) {
values.push(value);
({ value, done } = iterator.next());
}
console.log("limit=" + limit);
console.log("values=" + values.join(","));
Follow the Calls
limitstarts at3, andcurrentstarts at1.- Each
iterator.next()call returns an object withvalueanddone. - The loop pushes each value while
doneisfalse. - When
currentbecomes4, the next call returnsvalue: nullanddone: true. - The loop stops and prints
values=1,2,3. | call | returned value | returned done | loop action | | ---: | --- | --- | --- | | 1 | 1 | false | push 1 | | 2 | 2 | false | push 2 | | 3 | 3 | false | push 3 | | 4 | null | true | stop |
manual-iterator
An iterator returns one result at a time. Each call to `next` gives a value and a `done` flag.
Exercise: manual_iterator.js
Reproduce limit=3 and values=1,2,3, then use the pinned limits 2 and 4 to predict values=1,2 and values=1,2,3,4.