Throwing StopIteration in array extras to stop the iteration

David Bruant bruant.d at gmail.com
Sun Mar 3 12:01:47 PST 2013


Le 03/03/2013 20:29, Brendan Eich a écrit :
> If you want some or every and not forEach, they are there -- use them. 
> No exception required.
I've found myself multiple times in a situation where I needed the index 
of the first element responding to some conditions. I solved it the 
following way:

     var index;
     array.some(function(e, i){
         if(someCondition(e)){
             index = i;
             return false;
         }

         return true;
     })

It works, but felt a bit awkward. It's a hack on .some because there is 
no other way to stop an iteration in other array methods.
Also spending hours on debugging because someone confused "some" for 
"every" (mixed the meaning of true/false) isn't fun.

     var index;
     array.forEach(function(e, i){
         if(someCondition(e)){
             index = i;
             throw StopIteration;
         }
     })

would look more explicit in my opinion.

David


More information about the es-discuss mailing list