Created
May 30, 2019 09:30
-
-
Save zinevych/b39762cba4be9b97faad5c993095c2f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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