3 ms·
The 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
by lalaithion 5y ago
The 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)])