Open In App

Iterator Method | JavaScript Design Pattern

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Iterator: This is an interface that declares methods for traversing the elements of a collection.
  • ConcreteIterator: This is a specific implementation of the Iterator interface, providing the implementation for traversing the collection.
  • Client: The client is responsible for using the Iterator to traverse the elements of the collection without knowing its internal structure.
  • Items: These are the elements contained within the collection.

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.

Javascript




// 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

Untitled

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:

  • CustomList class: This class represents a custom list and has a property “list” initialized as an empty array in the constructor. It has a method “add” to add items to the list and a “getIterator” method that returns an instance of the “ListIterator” class, passing the current instance of the “CustomList” as a parameter.
  • ListIterator class: This class represents the iterator and takes an instance of “CustomList” as a parameter in its constructor. It has two methods: “hasNext”, which checks if there are more elements to iterate, and next, which returns the “next” element in the list and increments the index.
  • Client code: The client code initializes a new “CustomList”, adds some items to it, and then retrieves an iterator using the “getIterator” method. It then uses the iterator to iterate through the elements of the list using a “while” loop and logs each element to the console.

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

  • Simplifies the interface: It provides a uniform way to traverse different types of collections without exposing their internal structure.
  • Supports multiple simultaneous traversals: The same collection can be traversed in multiple ways concurrently using different iterators.
  • Encourages the use of polymorphism: It allows the client to work with different types of collections uniformly.

Disadvantages of the Iterator Pattern in JavaScript Design Patterns

  • Increased complexity: Implementing the Iterator pattern may introduce additional classes and complexity, especially for simple collections.
  • Overhead: In some cases, the use of iterators might introduce some overhead, although it’s usually negligible in most scenarios.

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads