loading...
Cover image for Iterator Pattern

Iterator Pattern

francescoxx profile image Francesco Ciulla ・1 min read

Iterator Design Pattern

Also known as Cursor

GitHub link: https://github.com/FrancescoXX/Design-Patterns-Iterator-Javascript


Behavioral Design Pattern

⚡️Recognize

We want to separate the logic of how to access data from data itself


💡Intent

Provide a way to access the elements of an aggregate object sequentially, without exposing its representation


🔧 Apply when

We want give a way to access elements in such a way that it does not expose its internal structure;
The Iterator takes the responsibility for access and manipulation of the data structure


✅Pro

  • We can define different iterators for different ways of manipulating a data structure
  • Clients can use an iterator to access data without knowing the representation

🏆 Great for

Decoupling algorithms from containers


/** Iterator Design Pattern
 *  Behavioral Pattern
 */

/**
 * @function hasNext returns true/false, depending 
 *                   if the iterator has other elements in the collection
 * @function next returns the next available element in the collection
 */
class Iterator {
  constructor(items) {
    this.items = items; //The collection to iterate to
    this.index = 0; //Starting index
  }

  hasNext = () => this.index < this.items.length; //Returns TRUE if there's another element, FALSE otherwise
  next = () => this.items[this.index++]; //Rule for next element
}

// MAIN

//Define a collection
const animals = ["dog", "cat", "bird", "tiger", "lion"];

//Define an Iterator
const iterator = new Iterator(animals);

//Iterate over each Element
while (iterator.hasNext()) {
  console.log("[", iterator.index, "] :", iterator.next());
}

// [ 0 ] : dog
// [ 1 ] : cat
// [ 2 ] : bird
// [ 3 ] : tiger
// [ 4 ] : lion



GitHub link: https://github.com/FrancescoXX/Design-Patterns-Iterator-Javascript

Posted on by:

Discussion

markdown guide