Skip to content

Instantly share code, notes, and snippets.

@SimonRichardson
Last active December 22, 2015 05:09
Show Gist options
  • Select an option

  • Save SimonRichardson/6421948 to your computer and use it in GitHub Desktop.

Select an option

Save SimonRichardson/6421948 to your computer and use it in GitHub Desktop.
Wrapper around Iterators/Generators in javascript so that we can find out if an iterator has a next value or not.
function Iter(machine) {
this.gen = machine();
this.current = this.__iterator__();
}
Iter.prototype.hasNext = function() {
return this.current.hasNext();
};
Iter.prototype.next = function() {
return this.current.next();
};
Iter.prototype.__iterator__ = function() {
var env = this,
values = [];
function Wrapper() {
this.hasNext = function() {
var possibleNext = true;
try {
values.push(env.gen.next());
} catch(e) {
if (e instanceof StopIteration) possibleNext = false;
else throw e;
}
return possibleNext;
};
this.next = function() {
if (values.length < 1) return env.gen.next();
else return values.shift();
};
}
return new Wrapper();
}
/*
To make it work:
function* a() {
for (var i = 0; i < 9; i++) {
yield i;
}
}
// Either way works!
var iter = new Iter(a);
while(iter.hasNext()) {
console.log(iter.next());
}
console.log('-------');
for(var i in new Iter(a)) {
console.log(i);
}
*/
@SimonRichardson
Copy link
Copy Markdown
Author

This is very stateful and not very functional, but considering that I believe exceptions should be in an exceptional condition and the proliferation of try...catch to know when a iterator has stopped is going to lead to painful code in most use cases!!

(own opinion not backed up by anything scientific at all)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment