Skip to content

Instantly share code, notes, and snippets.

@sergeykish
Created August 5, 2010 14:44
Show Gist options
  • Save sergeykish/509834 to your computer and use it in GitHub Desktop.
Save sergeykish/509834 to your computer and use it in GitHub Desktop.
JS iterators
low
high
__iterator__
undefined
Unknown thread
low
Unknown thread
high
Unknown thread
__iterator__
function Range(low, high) {
this.low = low;
this.high = high;
}
function RangeIterator(range) {
this.range = range;
this.current = this.range.low;
}
RangeIterator.prototype.next = function() {
if (this.current > this.range.high)
throw StopIteration;
else
return this.current++;
}
Range.prototype.__iterator__ = function() {
return new RangeIterator(this);
};
var range = new Range(3, 5);
for (var i in range)
console.log(i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment