Throwing StopIteration in array extras to stop the iteration

David Bruant bruant.d at gmail.com
Sun Mar 3 10:45:17 PST 2013


Hi,

One (minor) annoyance with forEach/map, etc. is that the enumeration 
"can't" be stopped until all elements have been traversed which doesn't 
suit every use case. One hack to stop the enumeration is to throw an 
error but that requires to wrap the .forEach call in a try/catch block 
which is annoying too for code readability.

The iterator protocol defines the StopIteration value. What about 
reusing this value in the context of array extras?

     (function(){
         [2, 8, 7].forEach(function(e){
             if(e === 8)
                 throw StopIteration;
             console.log(e)
         })

         console.log('yo')
     })();

In that case, '2' would be logged, then 'yo'. The idea is to have an 
in-function way to stop the iteration without being forced to throw 
something that has to be caught outside.
On the spec, for forEach, it would require to change step 7.c.ii. 
Probably looking at the completion value and if it's throw with a value 
of brand StopIteration, then don't forward the error and just stop the 
iteration.

For methods that return something, I guess the partially built 
array/value could be returned.

StopIteration is in Firefox (and that's not how it behaves with 
forEach&co) but in no other engine as far as I know, so it's not 
supposed to be part of the web, so I don't think there is a major issue 
preventing this change.

David


More information about the es-discuss mailing list