Iterating with the Iterator Pattern
The iterator design pattern allows sequential access to elements within a collection without revealing the collection’s internal workings. In other words, we manually choose when to extract the data of the next item. It’s common for this pattern to use a next() method that returns the next item in the collection. Some libraries even provide additional methods such as hasNext, isDone, first, and reset().
Step 1 – Implementing the Iterator
In iterator.js, we start by defining an Iterator constructor, which receives a collection of items and stores this collection as a property of the object. The object also has an index property initialized to 0 to track the items that have been processed. The iterator includes a set of methods:
- next(): Returns the next item in the collection and increments the index by 1.
- isDone(): Returns true once all the items in the collection have been iterated.
- reset(): Resets the index back to 0 for a fresh iteration.
- take(numberOfItems): Returns a specified number of items and updates the index accordingly.
We also define a factory pattern build method to handle various input types and create an appropriate iterator.
Step 2 – Initializing the Iterator
In init.js, we load the iterator and define test data, including an array and a string. We then use the build method to create iterators for each data set.
This implementation allows us to manually control the iteration process, enabling sequential data extraction whenever needed.
Step 3 – Utilizing the Iterator
The iterator can now be used in the main.js file. We can now call the iterator methods to iterate through the collections.