Open In App

Iterator Method | JavaScript Design Pattern

Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is widely used in many programming languages, including JavaScript, to manage collections and provide a consistent way of accessing their elements.

Key Component of Iterator Pattern in JavaScript Design Pattern

The Iterator pattern consists of the following key components:

Example for Iterator Pattern in JavaScript Design Patterns:

Consider a scenario where you have a custom data structure named “CustomList”, and you want to implement an iterator to traverse the elements of this list.






// CustomList class implementing the Iterable interface
class CustomList {
  constructor() {
    this.list = [];
  }
 
  add(item) {
    this.list.push(item);
  }
 
  getIterator() {
    return new ListIterator(this);
  }
}
 
// Iterator class implementing the Iterator interface
class ListIterator {
  constructor(list) {
    this.list = list.list;
    this.index = 0;
  }
 
  hasNext() {
    return this.index < this.list.length;
  }
 
  next() {
    return this.list[this.index++];
  }
}
 
// Client code
const customList = new CustomList();
customList.add("item1");
customList.add("item2");
customList.add("item3");
 
const iterator = customList.getIterator();
while (iterator.hasNext()) {
  console.log(iterator.next());
}

Output
item1
item2
item3


Output:

item1
item2
item3

Diagrammatic explanation of the Above Example

In this example:

We have implemented the Iterator design pattern in JavaScript using a custom “CustomList” class and an “ListIterator” class. The “CustomList” class acts as an iterable collection, while the “ListIterator” class is responsible for iterating through the elements of the collection.

Let’s break down the example step by step:

The client code can iterate through the elements of the “CustomList” without needing to know its internal implementation. The use of the Iterator pattern enables separation between the iteration logic and the data structure, making the code more modular and maintainable.

Advantages of the Iterator Pattern in JavaScript Design Patterns

Disadvantages of the Iterator Pattern in JavaScript Design Patterns

Conclusion

In conclusion, the Iterator design pattern is a powerful tool that allows for the traversal of collections without exposing their internal structure. Despite some potential drawbacks, it greatly enhances the flexibility and reusability of code when dealing with complex data structures.


Article Tags :