Throwing StopIteration in array extras to stop the iteration

# David Bruant (13 years ago)

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.

# Bjoern Hoehrmann (13 years ago)
  • David Bruant wrote:

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?

Using exceptions for normal flow control seems like a bad idea to me.

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

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

Languages like Haskell and C# would use takeWhile for this purpose, so you would have something like

[2, 8, 7].takeWhile(x => x !== 8).forEach(x => console.log(e));

That seems much better to me.

# David Bruant (13 years ago)

Le 03/03/2013 19:56, Bjoern Hoehrmann a écrit :

  • David Bruant wrote:

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? Using exceptions for normal flow control seems like a bad idea to me.

I could not agree more. But JavaScript is what it is. Iterators are going to use throw StopIteration [1] too. It's been discussed recently [2]. There could be slightly more radical ideas like the "endframe" thing I'm describing in the post, but I have no hope that such an idea would be considered seriously, that's why I haven't proposed it and only shared it as food for thought.

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

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

Languages like Haskell and C# would use takeWhile for this purpose, so you would have something like

[2, 8, 7].takeWhile(x => x !== 8).forEach(x => console.log(e));

That seems much better to me.

Sure. You can already prefix anything with .filter, but in current implementations and for the forseeable future, this systematically allocates an extra array (which in turn costs in terms of GC)

How would you make a takeWhile work in JS in a way that's as performant as throw StopIteration without breaking an existing website?

David

[1] harmony:iterators [2] esdiscuss/2013-February/028674

# Brendan Eich (13 years ago)

David Bruant wrote:

Le 03/03/2013 19:56, Bjoern Hoehrmann a écrit :

  • David Bruant wrote:

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? Using exceptions for normal flow control seems like a bad idea to me. I could not agree more. But JavaScript is what it is. Iterators are going to use throw StopIteration [1] too. It's been discussed recently [2]. There could be slightly more radical ideas like the "endframe" thing I'm describing in the post, but I have no hope that such an idea would be considered seriously, that's why I haven't proposed it and only shared it as food for thought.

You are barking up the wrong tree, again (same tree!).

This whole thread is a red herring. If you want some or every and not forEach, they are there -- use them. No exception required.

# David Bruant (13 years ago)

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.

# Brendan Eich (13 years ago)

(a) not a compatible change for engines already prototyping StopIteration. (b) wrong hammer for this nail.

Are the some and every names confusing? Would any and all be better?

I think this is an RTFM thing, and people are smart, they memorize what they need to know.

# Oliver Hunt (13 years ago)

On Mar 3, 2013, at 12:05 PM, Brendan Eich <brendan at mozilla.com> wrote:

(a) not a compatible change for engines already prototyping StopIteration. (b) wrong hammer for this nail.

Are the some and every names confusing? Would any and all be better?

I think the naming boat has sailed, and i'm not sure if any and all are superior anyway (the fact that this has come up is evidence of the similarity of the terms and futility of choosing one set of names to represent all things). If someone really cares about it they'll just make aliases like all/any/$woo/etc..

I think this is an RTFM thing, and people are smart, they memorize what they need to know.

Agreed.

# Bjoern Hoehrmann (13 years ago)
  • 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#.

# Rick Waldron (13 years ago)

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.

# Brendan Eich (13 years ago)

Bjoern Hoehrmann 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#.

Hi Bjoern, findIndex is indeed a missing Array generic. I'll see if we can get it on the agenda for the next TC39 meeting (coming up quickly, mid-March). Thanks,

# Andrea Giammarchi (13 years ago)

hacky but easy to solve reusing once a RegExp

var i = [1,2,3].some(function(v, i){ return v === 2 && this.test(i); }, /\d+/) && RegExp['$&'];

alert(i); // 1

no extra loop, no global anything, just an extra object needed, the RegExp, actually something you could create once in your closure and recycle every time you need.

br

# Andrea Giammarchi (13 years ago)
# Brendan Eich (13 years ago)

Andrea Giammarchi wrote:

hacky but easy to solve reusing once a RegExp

var i = [1,2,3].some(function(v, i){ return v === 2 && this.test(i); }, /\d+/) && RegExp['$&'];

My Perl 4 homage, blechh.

Thanks, this will help sell findIndex to TC39 :-P.

# Brendan Eich (13 years ago)

Brendan Eich wrote:

Andrea Giammarchi wrote:

RegExp['$&'];

My Perl 4 homage, blechh.

(You could at least have had the decency to use RegExp.lastMatch... ;-)

# Rick Waldron (13 years ago)

On Sun, Mar 3, 2013 at 5:33 PM, Brendan Eich <brendan at mozilla.com> wrote:

Bjoern Hoehrmann 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#.

Hi Bjoern, findIndex is indeed a missing Array generic. I'll see if we can get it on the agenda for the next TC39 meeting (coming up quickly, mid-March). Thanks,

Despite my previous message with a solution that relied on array.reduce(...), the benefit of stopping the iteration (once the predicate returns true) is objectively compelling.

# Brandon Benvie (13 years ago)

I was going to say...

indexOf with a callback is the best thing since sliced bread.

# Rick Waldron (13 years ago)

On Sun, Mar 3, 2013 at 9:38 PM, Brandon Benvie <bbenvie at mozilla.com> wrote:

I was going to say...

indexOf with a callback is the best thing since sliced bread.

Is this +1 to findIndex?

I ask because:

var a = function() {}, array = [a];

array.indexOf(a); // 0

# Andrea Giammarchi (13 years ago)

well, lastMatch is 9 chars against ['$&'] 6 but actually didn't know about lastMatch, it looks like to have more info about those properties, included lastParen, I had to check msdn rather than MDN since latter does not mention it while mans shows an example: msdn.microsoft.com/en-us/library/ie/3k9c4a32(v=vs.94).aspx

So, good to know ... in any case, I wrote that was hacky and usually hacky and looking good do not cope with each other ;-)

Also nobody mentioned here, neither I did in my post, about performance ... a for loop is at least twice as fast as any of these methods :-/

br

# Andrea Giammarchi (13 years ago)

had instantly same thought ... I use functions in Array very often to handle/manage asynchronous queues

br

# Jeff Walden (13 years ago)

On 03/03/2013 06:53 PM, Andrea Giammarchi wrote:

I had to check msdn rather than MDN since latter does not mention it while mans shows an example: msdn.microsoft.com/en-us/library/ie/3k9c4a32(v=vs.94).aspx

The RegExp statics aren't mentioned because they're a bad idea, imposing costs of some sort on pretty much all regular expression uses. Don't use them!

And, um, this is quite possibly the most awful way to find a value in an array that I've ever seen. Even setting aside the statics usage!

# Jeff Walden (13 years ago)

On 03/03/2013 06:49 PM, Rick Waldron wrote:

Is this +1 to findIndex?

Not that I much care between the two, just making sure another reasonable name is considered, but I'm not sure why it wouldn't be named "find" rather than "findIndex". The index seems like the only bit you'd reasonably be looking to find. (Well, maybe existence, but I'd expect a name like "contains" for that, or just indexOf !== -1.)

# Andrea Giammarchi (13 years ago)

I use RegExp.$1 , RegExp.$2, etc quite a lot since I am a huge fan of the RAM and I believe creating a redundant array of matches for no reason since these are retrievable in any case through the RegExp constructor, considering exec and match points to those RegExp properties anyhow, ain't needed when re.test(value) is involved.

If re.test(value) RegExp.$1;

As easy as that: 1) is not a bad practice and 2) is less redundant than if (re.test(value)) match = re.exec(value)[1];

I might agree about the ugly ness, the fact MDN is lacking those properties I believe defined in the specs does not mean those properties are bad (as I have just explained)

Also, that does not find a thing, that find an index ... and I forgot the +RegExp['$&'] plus sign to have the integer.

We are programmers, we find solutions/alternatives/optimizations ... right?

br

# Andrea Giammarchi (13 years ago)

" that does not find a thing, that find an index" I meant that simply store once the index without needing an outer scope access and variable inside the closure

# Bjoern Hoehrmann (13 years ago)
  • Jeff Walden wrote:

On 03/03/2013 06:49 PM, Rick Waldron wrote:

Is this +1 to findIndex?

Not that I much care between the two, just making sure another reasonable name is considered, but I'm not sure why it wouldn't be named "find" rather than "findIndex". The index seems like the only bit you'd reasonably be looking to find. (Well, maybe existence, but I'd expect a name like "contains" for that, or just indexOf !== -1.)

find finds the first element matching the supplied predicate in C#, Groovy, Haskell, and Scala, and the first element that is equal to the supplied value in C++, to mention a few examples. I think Python has a find method on strings that returns the index, but that's not generic.

# Rick Waldron (13 years ago)

On Mon, Mar 4, 2013 at 11:29 AM, Jeff Walden <jwalden+es at mit.edu> wrote:

On 03/03/2013 06:49 PM, Rick Waldron wrote:

Is this +1 to findIndex?

Not that I much care between the two, just making sure another reasonable name is considered, but I'm not sure why it wouldn't be named "find" rather than "findIndex".

Because "find' isn't "findIndex"—find would return the element, findIndex would return the index.

# Andrea Giammarchi (13 years ago)

this is what 've wrote as prototype at the end of the post. findIndex makes sense to me and is better, in term of manipulation, than finding just an element.

(function(AP){ AP.findIndex || ( AP.findIndex = function(fn, self) { var $i = -1; AP.some.call(this, function(v, i, a) { if (fn.call(this, v, i, a)) { $i = i; return true; } }, self); return $i; }; ); }(Array.prototype));

As you can see, and for consistency reasons, it returns -1 when the condition is not found.

Then we might discuss how useful would be a startFromIndex property but I believe the optional context is more useful than that (and indeed there are very few cases I needed that with Array#indexOf)

br

# Rick Waldron (13 years ago)

On Mon, Mar 4, 2013 at 2:37 PM, Andrea Giammarchi < andrea.giammarchi at gmail.com> wrote:

this is what 've wrote as prototype at the end of the post. findIndex makes sense to me and is better, in term of manipulation, than finding just an element.

(function(AP){ AP.findIndex || ( AP.findIndex = function(fn, self) { var $i = -1; AP.some.call(this, function(v, i, a) { if (fn.call(this, v, i, a)) { $i = i; return true; } }, self); return $i; }; ); }(Array.prototype));

As you can see, and for consistency reasons, it returns -1 when the condition is not found.

Then we might discuss how useful would be a startFromIndex property but I believe the optional context is more useful than that (and indeed there are very few cases I needed that with Array#indexOf)

Thanks, I've submitted an agenda item that includes both find and findIndex.

Rick

ps. @Andrea I also squeezed "unique" into the agenda addition ;)

# Domenic Denicola (13 years ago)

From: es-discuss-bounces at mozilla.org [es-discuss-bounces at mozilla.org] on behalf of Rick Waldron [waldron.rick at gmail.com]

Thanks, I've submitted an agenda item that includes both find and findIndex.

Awesome!

One issue with find is what distinguishes

find([1, 2, 3], x => isNaN(x)); // presumably `undefined`

from

find([1, 2, undefined, 3], x => isNaN(x)); // also presumably `undefined`

i.e. how do you distinguish "found nothing" from "found undefined."

In C# they have IEnumerable<T>.First and IEnumerable<T>.FirstOrDefault; the former throws an error if nothing matching the predicate is found, whereas the latter returns default(T) (which is null for reference types, or 0 for numbers, etc.).

Food for thought.

# Brendan Eich (13 years ago)

One idea we've discussed: allow the sentinel that is OOB with respect to the domain (element type) be an optional second parameter:

const K = Symbol("not found"); console.log( [1, 2, 3].find(x => isNaN(x), K) ); // K, logs as "not

found" console.log( [1, 2, , 3].find(x => isNaN(x)) ); // undefined

/be

P.S. Don't use isNaN! I know, it served your example's purpose.

# Andrea Giammarchi (13 years ago)

Thanks a lot.

On find(), I believe it will always be ambiguous, compared to findIndex, for the simple reason that an Array could contain undefined too [1, undefined, 2] ... probably an edge case not worth the consideration, but this looks like a legit code to me:

[1, undefined, 2].find(function (item) { return typeof item === 'undefined'; }) === undefined;

who knows if that was the undefined item, or the missing result ... not sure how to solve that ... just thinking about something like:

var found = /* same code */

if (Array.itemFound) { // use found } else { arr.push(createSomethingCool()); }

Array.itemFound would be "as ugly as RegExp.$N" and true until next [].find() call ... plus read only for the user. Well, this might work ... I guess

br

# Jeff Walden (13 years ago)

On 03/04/2013 08:38 AM, Andrea Giammarchi wrote:

I believe creating a redundant array of matches for no reason since these are retrievable in any case through the RegExp constructor, considering exec and match points to those RegExp properties anyhow, ain't needed when re.test(value) is involved.

You're saving on array-construction and element-creation, but you're losing (with many to most current engines) on having to re-run the regular expression a second time to compute the match components. You're almost certainly going to lose out overall when you take this extra cost into account. Array and string creation are fast in engines these days. Regular expression matching with the intent of constructing statics info is not.

Your code's also fragile against introduction of any other regular expressions within the code being demonstrated there. If someone copies your code and tries to change the === to a function-based test, they might well change it to something that uses regular expressions. That person might even be you: what's obvious now may not be obvious in the future.

If re.test(value) RegExp.$1;

As easy as that: 1) is not a bad practice and 2) is less redundant than if (re.test(value)) match = re.exec(value)[1];

To clarify the above, it's better to do:

var results = re.exec(value); if (results) results[1];

those properties I believe defined in the specs does not mean those properties are bad (as I have just explained)

They are not defined in spec, partly because you're mistaken about them being a good idea.

Also, that does not find a thing, that find an index ...

It's a fair point. Although, given non-existence, it would seem to me you'd only want a method that returns an index, and then getting the element value is just arr[index] at that point.

We are programmers, we find solutions/alternatives/optimizations ... right?

I'd also suggest we have the humility to recognize when we're trying to be too clever by half, as your forgotten "+" demonstrates.

# Jason Orendorff (13 years ago)

On Sun, Mar 3, 2013 at 12:45 PM, David Bruant <bruant.d at gmail.com> wrote:

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

This would be taking a piece of one low-level protocol, and using it for a sorta-kinda related thing that actually, on closer inspection, has nothing to do with that protocol. Array.prototype.forEach doesn't even use iterators.

# Andrea Giammarchi (13 years ago)

I didn't forget in the post, neither is necessary here, I put in the post to deal with an integer but that's superflous for the purpose so no mistake (we all know arr["1"] is gonna be handled as arr[1], as example)

Anyway, RegExp.$N is just fine and standard across all engines I know and RegExp#test() is more semantic than re.exec() plus it returns a boolean rather than compare a truthy/falsy value so .test() is correct if you expect exactly a boolean, not possible to be that explicit otherwise with exec.

The creation of an array can be not necessary and I code for mobile and Raspberry where RAM is gold and less GC kicks or less greedy too.

Accordingly, I will keep using RegExp.$N as long as every single engine will support it, without being forced by your personal taste to create a useless object plus we all know how many other problems a var in the scope could cause ... compare a var in the wild against RegExp access .. how better is really that?

Of course there are cases where exec is better, more readable, etc, and you have all these cases and reasons behind, in these good old slidess: webreflection.blogspot.de/2012/02/berlin-js-regexp-slides.html

I was missing the Brendan suggested property there and others, so I might update those slides.

Now, this thread is about something else, so that was just an alternative that makes the function portable and reusable, something the outer scope, your preferred solution, cannot do without polluting the scope and cannot be portable across different closures too ... but sure, I have to be humble while you cannot recognize your pattern might be undesired and not as flexible as mine, right ?

Mine is ugly? It's OK, it's an alternative .. and it works.

Now I am off this conversation, Best .

# David Bruant (13 years ago)

Le 05/03/2013 00:31, Jason Orendorff a écrit :

On Sun, Mar 3, 2013 at 12:45 PM, David Bruant <bruant.d at gmail.com <mailto:bruant.d at gmail.com>> wrote:

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

This would be taking a piece of one low-level protocol, and using it for a sorta-kinda related thing that actually, on closer inspection, has nothing to do with that protocol. Array.prototype.forEach doesn't even use iterators.

I could not agree more. I'm aiming at a least-worst type of solution, rather than something good.

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 }

  1. (ab)using some and every

Downsides to each solution

  1. If you care about good use of protocols, I hope you'll agree that the try/catch protocol is severely abused

Brendan wrote:

Are the some and every names confusing? Would any and all be better?

The problem is that there are 2 of them and stopping the iteration is returning true in one case, false in the other. People are smart, memorize what they need to know. I know I spend more time reading some/every code than normal just to be sure of what true and false means. It might be because I'm not a native English speaker that I have to extra-think on every/some, but that's not an excuse anyway.

"return true/false" to stop an iteration early does not make very readable code. Recently, I was helping a friend with some code he needed help to fix. Code that had been written in team. He asked me "but how do you know where the problem is without having to read all the code?". To which I answered "Do you see the 'queue.persist()'? I know it persists the queue and does nothing else, I don't need to read that code". I wish whenever I want to stop an iteration early, I didn't have to flip a coin to choose some and every and the corresponding true/false semantics but had something as readable as queue.persist to say what I mean.

I thought I was doing a clever "language hack" by reusing 'throw StopIteration' exactly in a context where it's not supposed to have a meaning. Apparently I was not.

I'm happy of the outcome of the thread if .findIndex is introduced, but I can't help wondering whether a new method is going to be introduced every single time someone brings up a pattern that would make good use of stopping an interation early.

# Brendan Eich (13 years ago)

David Bruant wrote:

I'm happy of the outcome of the thread if .findIndex is introduced, but I can't help wondering whether a new method is going to be introduced every single time someone brings up a pattern that would make good use of stopping an interation early.

Lacking an iteration protocol, that's the natural tendency, although there are only so many methods and method-variations likely to be needed.

With for-of, stopping early is done by a break in the body.

Inventing synonyms for exceptions (endframe) or adding escape continuations for more locally structured control effects could be done, but why? I think we're nearly "done" (no pun!).

# Jason Orendorff (13 years ago)

On Tue, Mar 5, 2013 at 5:42 AM, David Bruant <bruant.d at gmail.com> 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?

# Kevin Gadd (13 years ago)

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

# David Bruant (13 years ago)

Le 05/03/2013 18:32, Jason Orendorff a écrit :

On Tue, Mar 5, 2013 at 5:42 AM, David Bruant <bruant.d at gmail.com <mailto:bruant.d at gmail.com>> 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?

I love the idea of for-of, and that's probably what I'll use in the future indeed (for-of isn't available since 1994 ;-) )

I've realized that in a recent Node.js experience I had made no off-by-one errors and I consider the extensive use of forEach&friends to be the reason for that. The iterator protocol and for-of loops by extension provide the same guarantee that forEach (with the possibility to break) so I guess I'll use that whenever possible.

Thanks,

# Tab Atkins Jr. (13 years ago)

On Tue, Mar 5, 2013 at 9:38 AM, Kevin Gadd <kevin.gadd at gmail.com> wrote:

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

Additional upside: we can canonically call the argument "halt", thus finally completing Brendan's name in forEach's signature: forEach(Element, Index, Collection, Halt). ^_^

# Andrea Giammarchi (13 years ago)

love the token/Halt idea +1 easy to polyfill too

However, and this is for David, some and every are not the opposite. With some, you return true only when you want to exit, with every you have to return true or false accordingly.

So, the return true in Array#some() is the equivalent of a break, while no return false is necessary.

This is not the case of every, where the first time you don't return true, you are out.

You know that but I just wonder how come you think these methods are confusing, I think these are OK.

br

# David Bruant (13 years ago)

Le 05/03/2013 17:37, Brendan Eich a écrit :

David Bruant wrote:

I'm happy of the outcome of the thread if .findIndex is introduced, but I can't help wondering whether a new method is going to be introduced every single time someone brings up a pattern that would make good use of stopping an interation early.

Lacking an iteration protocol, that's the natural tendency, although there are only so many methods and method-variations likely to be needed.

With for-of, stopping early is done by a break in the body.

Indeed. The mention of the lack of an iteration protocol made me realize that maybe .forEach was just a detour (map/reduce/filter/every/some answer to a specific pattern, so they're still useful)

Inventing synonyms for exceptions (endframe) or adding escape continuations for more locally structured control effects could be done, but why? I think we're nearly "done" (no pun!).

Discriminating how a frame ended by value works. There is the concern about cross-frame protocols and we're saved by [[Brand]] which is a forgeable string that's the same cross-globals. But authors don't have this kind of control. Maybe we'll never need to extend JavaScript with other function-based protocols because hacking "return true/false" (considered so many times for proxy traps) and "throw StopIteration" will be enough. I don't have a better name than "function-based protocols", but I feel we're not done with them. We might be just starting. We'll see.

# Brendan Eich (13 years ago)

Jason Orendorff wrote:

        break;   // exiting JS loops since 1994

1995!

# Jason Orendorff (13 years ago)

On Tue, Mar 5, 2013 at 6:57 PM, Brendan Eich <brendan at mozilla.com> wrote:

Jason Orendorff wrote:

        break;   // exiting JS loops since 1994

1995!

Mercurial logs only go back to 2007, CVS only to 1998, so I will have to take your word for it! :)