3 ms·
I just filed this issue on the MDN page: https://github.com/mdn/content/issues/11763 https://github.com/mdn/content/issues/11763 That note is misleading.
by hildjj 5y ago
I just filed this issue on the MDN page: https://github.com/mdn/content/issues/11763 https://github.com/mdn/content/issues/11763
That note is misleading.
- edflsafoiewq 5y agoIt still creates a temporary [x, 2*x] array for every element though. This is an unavoidable problem with flatMap, while reduce can easily be changed to reuse the same accumulator array, making it twice as fast as flatMap and almost as fast as the simple for-loop approach.
- Osiris 5y agoMy preference for when I have to do multiple operations on the same array (like filter then map) is "reduce". It's the most straightforward way other developers will understand what's going on.
- eyelidlessness 5y agoNot that I disagree with your preference, in fact I share it. But this: > It's the most straightforward way other developers will understand what's going on. … has been the opposite of my experience. Both on the job (where I’ve always conceded to team preference for imperative loops) and observing the community (hating on reduce is a whole meme on JavaScript/TypeScript Twitter, and the contrary meme has never shown up at least on my feed). And I honestly understand why it’s not very popular. Reduce/fold is a very FP concept which isn’t particularly idiomatic in real world JS. When I learned and embraced it (myself coming from a JS background), it took dozens of real uses before I felt like I had committed to my own memory what’s actually happening. And by then I think I was writing Clojure.
- dragonwriter 5y ago> My preference for when I have to do multiple operations on the same array (like filter then map) is "reduce". It's the most straightforward way other developers will understand what's going on. There are definitely operations that are more intuitive as reduces, but any sequences consisting of exclusively filter, map, and/or flatMap are, IME and IMO, about the worst candidates. (That said, because the JS filter, map, etc. operations are eager rather than lazy, sequenced operations produce intermediate arrays that may be undesirable especially with large datasets, so reduce can be desirable even without being more clear in intent.)