THE ITERATOR PATTERN
The iterator pattern (specifically in the context of ECMAScript) describes a solution in which something can be described as “iterable” and can implement a formal Iterable
interface and consumed by an Iterator
.
The concept of an “iterable” is intentionally abstract. Frequently, the iterable will take the form of a collection object like an array or set, both of which have a finite number of countable elements and feature an unambiguous order of traversal:
// Arrays have finite countable elements
// In-order traversal visits each index in increasing index order
let arr = [3, 1, 4];
// Sets have finite countable elements
// In-order traversal visits each value in insertion order
let set = new Set().add(3).add(1).add(4);
However, an iterable does not have to be linked to a collection object. It can also be linked to something that only behaves like an array—such as the counting loop from earlier in the chapter. The values generated...