Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Iterators

Tags:

javascript

I was going through MDN (Mozilla Developer Network) and came across Iterators and generators

So naturally, I tried the snippets of code given in the page on Google Chrome v21. To be specific, this code:

var it = Iterator(lang);
for (var pair in it)
  print(pair); // prints each [key, value] pair in turn

However, the console returns this error message:

ReferenceError: Iterator is not defined

Why's that? Is the Iterator function deprecated or something? Am I missing a point? Thank you for your help and time :-)

like image 735
Hirvesh Avatar asked Aug 22 '12 18:08

Hirvesh


1 Answers

Arrays have a built in map function that acts like an iterator.

[1,2,3].map(function(input){console.log(input)});

Standard Out:

1
2
3

Worst case you could easily design an iterator object, didn't full test this but if there are any bugs you should be able to quickly get this working.

var Iterator = function(arr){ return {
    index : -1,
    hasNext : function(){ return this.index <= arr.length; },
    hasPrevious: function(){ return this.index > 0; },

    current: function(){ return arr[ this["index"] ]; },

    next : function(){
        if(this.hasNext()){
            this.index = this.index + 1;            
            return this.current();
        } 
        return false;
    },

    previous : function(){
        if(this.hasPrevious()){
            this.index = this.index - 1
            return this.current();
        }
        return false;
    }
}   
};

var iter = Iterator([1,2,3]);

while(iter.hasNext()){
    console.log(iter.next());
}
like image 88
Dan Avatar answered Sep 18 '22 18:09

Dan