Last active
August 29, 2015 13:56
-
-
Save getify/9335735 to your computer and use it in GitHub Desktop.
could generators have a default iterator?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Right, the point is just a simple default, just as other data structures get default @@iterator
s (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
Seems sane, assuming your generator doesn't require any arguments I suppose?