Re: Why can’t for-of be applied to iterators?

Axel Rauschmayer axel at rauschma.de
Sat Jun 8 23:39:18 PDT 2013


>> I can’t find the rationale as to why that isn’t allowed. Is it because iterators can’t be recognized as safely as iterables?
> 
> Both Iterators and Iterables may be ordinary objects.  There has to be some way for for-of to recognize one or the other. The way that an Iterable is recognized is by the presence of an @@iterator method. An Iterator is only required to have a "next" method. Checking for the unique symbol @@iterator seems much less likely to produce false positives then checking for "next".

True, @@iterator is a much better “type tag”. If @@iterator is checked first, would false positives really be a problem?

>> If we did enable for-of (and Array.from) for iterators, we would get two advantages:
>> 
>> - Generators would not need to have a method @@iterator.
> 
> why is this a big deal?  It is provided by the standard generator prototype that all generators inherit from.

It’s not that big of a deal, I just prefer the increased conceptual clarity (which may or may not be worth the additional complexity).

>> - Many functions actually return iterators, but have to turn them into iterables (by adding a method @@iterator that returns `this`) to work with for-of.
> 
> As a rule of thumb, if an Iterator is produced by a @@iterator method it probably doesn't need to also be an Iterable.  If an Iterator is produced by any other method it probably should be an Iterable.
> 
> It seems easy enough to define a class that has a @@iterator() {return this} method and then to subclass class it for you specific Iterables.

True.

Another use case for iterator support: retrieve the first element from an iterator, then iterate over the remaining elements via for-of.

-- 
Dr. Axel Rauschmayer
axel at rauschma.de

home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130609/dc6fe5b6/attachment.html>


More information about the es-discuss mailing list