The iterator pattern allows us access to the elements in a collection without exposing its underlying representation.
In the example below, we will create a simple iterator with an array of elements. We can iterate through all the elements using the methods next() and hasNext().
class Iterator {
constructor(el) {
this.index = 0;
this.elements = el;
}
next() {
return this.elements[this.index++];
}
hasNext() {
return this.index < this.elements.length;
}
}
A complete example is here ๐ https://stackblitz.com/edit/vitejs-vite-2txuqu?file=iterator.js
๐ Using this pattern when we want to access an objectโs content collections without knowing how it is internally represented.
I hope you found it helpful. Thanks for reading. ๐
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (11)
There's no need to create a non-standard wrapper around an array โ just use the built-in
Symbol.iterator
method:Or even simpler (if arguably a bit hacky):
Thanks for sharing, Nhan! Btw, the illustration seems came from Refactoring Guru webaite and I think a simple credit should make the author feels appreciated ๐
I bought a Dive Into Design Patterns book from Refactoring.Guru ๐
That's awesome! I love that book also. But, I don't know if we already bought, we are allowed to use those attributes. It reminds me when I put illustration from Refactoring UI then someone suggested me to put credit because it's licenced.
Thank you for sharing about this website. Found very usefull
Iterators can be an interesting topic, it can be much cleaner than creating and populating an array. It is especially helpful if you are creating an unlimited sequence or progression of numbers.
When developing an iterator, the next logical step is to look at built-in iteration protocols. Implementing these allows standard Iterable consumers like
Array.from()
and spread operators.Also, please be aware of copyright concerns when using content or illustrations from other sources.
This is a non-standard approach, so custom that will not integrate well with the language capabilities. It could be useful for learning purposes but a better approach is to follow the iteration protocol. That is the standard way to hide your implementation behind something similar to your idea but compatible with
forโฆof
loops, for instance.It's a plus is my programming ,adventure.
Excellent your Iterator class. Javascript classes are great. I recommend them always to fix the functional programming spaghetti
This post may contain uncredited images. Failure to properly attribute all visual content violates our policies and may result in account suspension.