Iterator

Sequentially access the elements of a collection.

  • Provide a way to access the elements of an aggregate/collection object sequentially without exposing its underlying representation.

  • Most frequently used in Javascript.

  • The Iterator pattern allows clients to effectively loop over a collection of objects.

  • The Iterator pattern allows JavaScript developers to design looping constructs that are far more flexible and sophisticated.

EX:
var Iterator = function(items) {
    this.index = 0;
    this.items = items;
}
 
Iterator.prototype = {
    first: function() {
        this.reset();
        return this.next();
    },
    next: function() {
        return this.items[this.index++];
    },
    hasNext: function() {
        return this.index <= this.items.length;
    },
    reset: function() {
        this.index = 0;
    },
    each: function(callback) {
        for (var item = this.first(); this.hasNext(); item = this.next()) {
            callback(item);
        }
    }
}

function run() {
    var items = ["one", 2, "circle", true, "Applepie"];
    var iter = new Iterator(items);
 
    // using for loop
 
    for (var item = iter.first(); iter.hasNext(); item = iter.next()) {
        console.log(item);
    }
 
    // using Iterator's each method 
    iter.each(function(item) {
        console.log(item);
    });
}

run();

Last updated