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 C
var makeIterator = function (collection, property) {
var agg = (function (collection) {
var index = 0;
var length = collection.length;
return {
next: function () {
var element;
if (!this.hasNext()) {
return null;
}
element = collection[index][property];
index = index + 1;
return element;
},
hasNext: function () {
return index < length;
},
rewind: function () {
index = 0;
},
current: function () {
return collection[index];
}
};
})(collection);
return agg;
};
var iterator = makeIterator([5,8,4,2]);
console.log(iterator.current())//5
console.log( iterator.next() )
console.log(iterator.current()) //8
console.log(iterator.rewind());
console.log(iterator.current()) //5