3 ms·
You could do that, but I’d argue using filter then map is more readable. What do empty arrays have to do with doubling even integers?
by niek_pas 5y ago
You could do that, but I’d argue using filter then map is more readable. What do empty arrays have to do with doubling even integers?
- lalaithion 5y agoThe interesting generalization is that once you realize that flatMap lets you map and filter at the same time is that you can generate arbitrary elements in the output list corresponding to each item in the input list. For example, ls.flatMap(x => { if (x < 0) { return [] } else if (x == 0) { return [0] } else { return [Math.sqrt(x), -Math.sqrt(x)] } }) gives you all the real square roots from the original list, doing the mapping, flattening, and filtering all in one function call.
- 6510 5y ago(just for laughs) ls.filter(o=>0<o).map(o=>o||[Math.sqrt(x, -Math.sqrt(x)])
- nefitty 5y agoI agree on the readability. There's a TC proposal floating around for a pipeline operator. I don't think it's moved but that would be a game changer.
- frozenlettuce 5y ago>What do empty arrays have to do with doubling even integers nothing, but they do have some relationship to 0, "" and Promise.resolve() - the array is handling the logic that will make the results be combined, not the doubling part
- hajile 5y agoFilter and then map will iterate the list twice. JS really needs some iterator-based methods like Lodash where it will only go through the list once in this case.