Maybe I'm overlooking some past discussion on this, but if you want to
be able to generally terminate iteration in constructs like
Array.forEach (this seems like a pretty real world use-case), why not
introduce an additional argument to the forEach/etc callbacks, for an
'iteration token'?

I.e. if forEach currently passes 'item, index, array' to the callback,
it can pass 'item, index, array, token'. token can be an object, such
that:

token.stopIteration(); // probably a better name for this

terminates iteration.

This has some upsides:
You can mechanically detect a conforming implementation by looking for
the token object via arguments[3]
There's no risk of code written for a conforming implementation
causing weird side effects (like an uncaught StopIteration) in a
non-conforming iteration; it'll fail meaningfully
The token is conceptually easy to understand and the implementation cost is low

-kg

On Tue, Mar 5, 2013 at 9:32 AM, Jason Orendorff
<[email protected]> wrote:
> On Tue, Mar 5, 2013 at 5:42 AM, David Bruant <[email protected]> wrote:
>>
>> Currently, if one wants to do stop an iteration early, he/she has to be
>> done one of the following way:
>> 1)
>>     try{
>>
>>         [2, 8, 7].forEach(function(e){
>>                 if(e === 8)
>>                     throw "whatever";
>>                 console.log(e)
>>         }
>>     }
>>     catch(e){
>>         // do nothing, I just want to catch the error in case the
>> iteration
>>         // stopped before traversing all elements
>>     }
>
>
> Well... here's what I would do.
>
>     for (var e of [2, 8, 7]) {
>         if (e === 8)
>             break;   // exiting JS loops since 1994
>         console.log(e);
>     }
>
> Why not use statements for your procedural code?
>
> -j
>
>
> _______________________________________________
> es-discuss mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/es-discuss
>



-- 
-kg
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to