Throwing StopIteration in array extras to stop the iteration

Rick Waldron waldron.rick at gmail.com
Sun Mar 3 13:57:34 PST 2013


On Sun, Mar 3, 2013 at 3:34 PM, Bjoern Hoehrmann <derhoermi at gmx.net> wrote:

> * David Bruant wrote:
> >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's usually a bad idea to trigger side-effects from such callbacks. The
> proper solution here would be having a suitable method available, like
>
>   var index = array.findIndex(someCondition);
>
> as it is called in Haskell and C#.
>

This can be easily accomplished with Array.prototype.reduce:

function evaluate(str) {
  return str === "b";
}

var array = [ "a", "b", "c" ];

var index = array.reduce(function(idx, val, i) {
  return (idx === -1 && evaluate(val) && i ) || idx;
}, -1);

console.log( index ); // 1


But this won't stop the iteration, of course.


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130303/5b59b8d4/attachment.html>


More information about the es-discuss mailing list