Skip to content

Instantly share code, notes, and snippets.

@zinevych
Created May 30, 2019 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zinevych/b39762cba4be9b97faad5c993095c2f8 to your computer and use it in GitHub Desktop.
Save zinevych/b39762cba4be9b97faad5c993095c2f8 to your computer and use it in GitHub Desktop.
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