archives

« Bugzilla Issues Index

#3015 — Default iterator for generators?


Could generators (the function objects themselves) have a default iterator (actually on GeneratorFunctionPrototype), which just invokes the iterator itself?

For example:


(function*(){}).__proto__[Symbol.iterator] = function(){ return this.apply(this,arguments); };


That would make generators a tad more consistent with other data structures (like arrays, for instance) which have a default iterator.

Now, if you have a `for..of` loop that can either iterate over a generator or an array (or other structures with built-in/default iterators), you don't need to fork to manually get the iterator for the loop. This is very nice:


function drainIterator(o) {
for (var v of o) {
console.log(v);
}
}

drainIterator( [1,2,3] ); // 1 2 3
drainIterator( function*(){ yield 1; yield 2; yield 3; } ); // 1 2 3


Short of making my own default iterator (like above), which feels "wrong", I have to fork logic in such a utility:


function drainIterator(o) {
var it;

if (typeof o === "function") it = o();
else it = o[Symbol.iterator]();

for (var v of it) {
console.log(v);
}
}


Works, but less attractive.

Having the default iterator on the GeneratorFunctionPrototype object, as shown, certainly wouldn't prevent you from calling the generator to make an iterator for the loop (`for (var v of foo(42)) { .. }`), it would just make the default case optional.


sorry, correction: "which just invokes the generator itself"


Proposals should use the proposal process documented here: https://github.com/tc39/ecma262/blob/master/CONTRIBUTING.md.