Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
accessor properties (getter/setters) used to create a simple iterators. Inspired by @eu96ne
/*
* A limited example of using getters/setters as a way to iterate over a range
* some background info at: freeman.blogspot.com/2013/07/javascript-getters-and-setters-last.html
*/
// Simple Array Iterator
//
// Expects array
var SimpleArrayIterator = function(arr){
this.arr = arr;
this.currentIdx = 0;
}
SimpleArrayIterator.prototype = {
get next() {
if(this.hasMore){
return this.arr[this.currentIdx++];
}
else {
throw new Error('Reached the End!');
}
},
get hasMore(){
return this.currentIdx < this.arr.length;
},
reset: function(){
this.currentIdx = 0;
}
}
//Usage:
var tags = ['vma', 'scandal', 'twerking'];
var tagIter = new SimpleArrayIterator(tags);
while(tagIter.hasMore){
console.log(tagIter.next);
}
tagIter.next; // throws error
tagIter.reset();
tagIter.next; // returns 'vma'
/*
* A limited example of using getters/setters as a way to iterate over a range
* some background info at: freeman.blogspot.com/2013/07/javascript-getters-and-setters-last.html
*/
// Simple Range Iterator
//
// Expects low and high or just high (assumes low is 0)
var SimpleRangeIterator = function(low, high){
if(!high) {
high = low;
low = 0;
}
this.low = this.current = low;
this.high = high;
}
SimpleRangeIterator.prototype = {
get next(){
if(this.current > this.high){
throw new Error('Reached the End!');
}
else {
return this.current++;
}
},
get hasMore(){
return this.current <= this.high;
},
reset: function(){
this.current = this.low;
}
}
// Usage:
var toTen = new SimpleRangeIterator(10);
while(toTen.hasMore){
console.log(toTen.next);
}
toTen.next; // throws error
toTen.reset();
toTen.next; // returns 0
// or
var fiftyToSixty = new SimpleRangeIterator(50, 60);
while(fiftyToSixty.hasMore){
console.log(fiftyToSixty.next);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.