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] http://wiki.ecmascript.org/doku.php?id=harmony:iterators
[2] https://mail.mozilla.org/pipermail/es-discuss/2013-February/028674.html
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to