Throwing StopIteration in array extras to stop the iteration

Bjoern Hoehrmann derhoermi at gmx.net
Sun Mar 3 10:56:26 PST 2013


* 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.
-- 
Björn Höhrmann · mailto:bjoern at hoehrmann.de · http://bjoern.hoehrmann.de
Am Badedeich 7 · Telefon: +49(0)160/4415681 · http://www.bjoernsworld.de
25899 Dagebüll · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/ 


More information about the es-discuss mailing list