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

Allen Wirfs-Brock allen at wirfs-brock.com
Tue Jun 11 10:53:16 PDT 2013


On Jun 11, 2013, at 9:41 AM, Brandon Benvie wrote:

> On 6/11/2013 5:50 AM, Tab Atkins Jr. wrote:
>> On Tue, Jun 11, 2013 at 2:08 AM, Axel Rauschmayer <axel at rauschma.de> wrote:
>>> On the other hand, turning every iterator into an iterable puts the burden
>>> on people implementing iterators: they have to implement the iterable
>>> interface.
>> That's... not really a burden.  It's literally just adding an
>> @@iterator method whose body is "return this;".  It's the right place
>> to put the burden, too - manual iterator authors are much, much fewer
>> than for-of users.
> 
> It may be worth noting that, while it hasn't made it into the ES6 spec (yet?), the iterators strawman [1] (and modules_standard strawman [2]) had an `Iterator` class that all the builtin iterators (Map, Set, Generator, etc.) inherited from who's prototype had @@iterator built in. So usually the only burden for iterator authors was to create a class that inherited from Iterator.
> 
>    import { Iterator } from '@iter';
>    class MyIterator extends Iterator { /*...*/  }

t would be trivial to specify an Iterator abstract class of this sort and I personally would be fine having it. However, I don't think we have consensus yet that it is desirable to include such abstract classes in the ES standard library.
Currently, in the spec draft, the built-in collection Iterators all  individually implement @@iterator() {return this} 

Note that such an abstract class is even a reasonable substitute for use of an object literal to define an iterator:

import {Iterator} from "standard iteration module";
function giveMeAEmptyIterator( ) {
   return new class extends Iterator {
       next() {return {done: true}}
   }
}

rather than:

import {iteratorSymbol} from "standard iteration module";
function giveMeAEmptyIterator( ) {
   return  {
       next() {return {done: true}},
       [iteratorSymbol] () {return this}
   }
}

But, really, for-of (and Arrray.from and friends) should just accept either an Iterable or an Iterator with priority given to Iterable 

Then the above an most conveniently be coded as:

function giveMeAEmptyIterator( ) {
   return  {
       next() {return {done: true}},
   }
}

The for-of behavior should be:
      If ducktype check of the "of" value) is true use result of invoking @@iterator on the "of" value as the Iterator
      else use "of" value as the Iterator

This is a very cheap test and only occurs once on entry to a loop

Allen
     





> 
> 
> [1] http://wiki.ecmascript.org/doku.php?id=harmony:iterators
> [2] http://wiki.ecmascript.org/doku.php?id=harmony:modules_standard
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
> 



More information about the es-discuss mailing list