Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

JavaScript has generator functions. Comprehensions are really just sugar around this functionality. You could pretty easily write your own set of generator function-powered methods for mapping and filtering.


Which I've started doing, but it is still a real shame that the "default way" is so inefficient, especially given how many devs never even realize it. It contributes a whole lot of accidental-slowness to the ecosystem.


> the "default way" is so inefficient

A big reason why I say screw map, filter, reduce, etc. and my "default way" never stopped being ordinary for loops.


bastawhiz's (correct) point is that it's easy in JS to have the best of both worlds: write your code as multiple, decoupled passes, with the performance of a for loop. The only problem is that in JS you have to go out of your way to do it. But those of us who know about it can, and generally should, do so.


Though I have found generators in JS often come with an overhead compared to a well-written for loop. (Some languages like rust or Julia will inline all the closures for you and remove all the overhead).

Still a great way to avoid intermediate allocations, though.


can you point me to a good tutorial showing how to do this? i'm a conflicted web dev regarding loops. I love the simplicity that map/filter have, but I hate that they require looping over the same array more than once, which makes me choose for loops over them... Never thought I could have the best of both worlds




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: