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

  1. limit starts at 3, and current starts at 1.
  2. Each iterator.next() call returns an object with value and done.
  3. The loop pushes each value while done is false.
  4. When current becomes 4, the next call returns value: null and done: true.
  5. 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.