Skip to content

Instantly share code, notes, and snippets.

@zinevych
Created May 30, 2019
Embed
What would you like to do?
var Iterator = function(items) {
this.index = 0;
this.items = items;
}
Iterator.prototype = {
first: () => {
this.reset();
return this.next();
},
next: () => {
return this.items[this.index++];
},
hasNext: () => {
return this.index <= this.items.length;
},
reset: () => {
this.index = 0;
},
each: (callback) => {
for (var item = this.first(); this.hasNext(); item = this.next()) {
callback(item);
}
}
}
//--------------------
function run() {
let items = [“one", 2, "circle", true, "Applepie"];
let iter = new Iterator(items);
// using for loop
for (let item = iter.first(); iter.hasNext(); item = iter.next()) {
//some action here
}
// using Iterator's each method
iter.each((item) => {
//some action here
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment