Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 29, 2015 13:56
Show Gist options
  • Save getify/9335735 to your computer and use it in GitHub Desktop.
Save getify/9335735 to your computer and use it in GitHub Desktop.
could generators have a default iterator?
// this works
function* foo() {
yield 1;
yield 1;
yield 3;
yield 5;
yield 8;
yield 13;
yield 21;
}
// note: i called `foo()` to get the iterator
for (var x of foo()) {
console.log(x);
}
// 1 1 3 5 8 13 21
// this doesn't work, but it could work, right?
function* foo() {
yield 1;
yield 1;
yield 3;
yield 5;
yield 8;
yield 13;
yield 21;
}
// note: generator could have a default @@iterator which
// just invokes the generator itself, right?
//
// as it stands, without calling `foo()`, this is an error!
for (var x of foo) {
console.log(x);
}
// fake a default iterator for the generator,
// which is just calling itself
(function*(){}).__proto__[Symbol.iterator] = function(){ return this.apply(this,arguments); };
// but, this works
function* foo() {
yield 1;
yield 1;
yield 3;
yield 5;
yield 8;
yield 13;
yield 21;
}
// now this works great!
for (var x of foo) {
console.log(x);
}
// 1 1 3 5 8 13 21
@bterlson
Copy link

bterlson commented Mar 4, 2014

Seems sane, assuming your generator doesn't require any arguments I suppose?

@getify
Copy link
Author

getify commented Mar 4, 2014

Right, the point is just a simple default, just as other data structures get default @@iterators (like array and object). If your generator needs args, you can always do:

for (var x of foo(2,3,4)) {
   console.log(x);
}

And of course, if you want to make a different kind of default @@iterator, you can override per generator:

function* foo(a,b) { /* .. */ }
foo[Symbol.iterator] = function() { return foo(2,4); };

// ...

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