Check out Dart's iterators

David Bruant bruant.d at
Sun Feb 10 13:01:35 PST 2013

Le 10/02/2013 20:55, Oliver Hunt a écrit :
> Just a couple of questions on this wonderous topic:
> * how is 'e instanceof StopIteration' intended to work across multiple global objects?
StopIteration has a special "StopIteration" [[Brand]] [1], so the 
cross-global story shouldn't be a problem for the for-of loop.
Exposing the brand can solve the problem for manual use of iterators. 
(you'd check if the object has a particular brand instead of "e 
instanceof StopIteration").

StopIteration could also be a deeply frozen constructor with same 
identity across globals.

> * how firmly are we wedded to this? I can't imagine there is too much code that currently depends on manually catching StopIteration given ES6 is not finalized yet, and iterators aren't widely available.
> I do dislike the exception based termination, I _think_ i'd prefer next() and hasNext() style iteration over exceptions, especially given that for the most part these are hidden by clean syntax.
The "for the most part these are hidden by clean syntax" argument 
applies to throwing StopIteration too, no?

> My personal concern with all of these is how they deal with nested iterators.
I don't see the concern. Can you provide a use case/code sample where 
nested iterators would be a problem?

I have to note that there is a minor security hazard in code using 
iterators naively:
     import process from "m";

     var a = [1, 2, 3, 4, 5];
     var next = 0;
     var it = {
         next: function(){
             if(next < a.length){
                 // If the call to "process" throws StopIteration 
because it's malicious/buggy,
                 // so does this code and that's largely unexpected.
                 return process(a[next++]);
                 throw StopIteration;

You can always protect yourself by wrapping the call to "process" with a 
try/catch block.
I'm still on the side of preferring "throw StopIteration" for its better 
readability compared to "return false". Dart has "implements 
Iterator<T>" to help, but JavaScript doesn't.



More information about the es-discuss mailing list