Iterators the easy way
Writing next() by hand is fiddly. A generator function (with an asterisk) can pause at each yield and pick up where it left off — and it's automatically an iterator.
function* and yield
function* steps() {
yield "Boil water";
yield "Add tea";
yield "Pour";
}
const it = steps();
console.log(it.next().value);
console.log([...it]);
function* range(from, to) {
for (let n = from; n <= to; n++) yield n;
}
console.log([...range(1, 5)]);function* ids() {
let id = 1;
while (true) yield id++;
}
const nextId = ids();
console.log(nextId.next().value, nextId.next().value, nextId.next().value);