3 ms·
In this example it is, but a nice thing about using map, reduce etc is that you can chain them together, ex: let out = ["a", "b", "c", 1, 2, 3] // Turn le
by ablomen 9y ago
In this example it is, but a nice thing about using map, reduce etc is that you can chain them together, ex:
let out = ["a", "b", "c", 1, 2, 3]
// Turn letters to upper case
.map(i => {
return typeof i === "string"
? i.toUpperCase()
: i;
})
// Add one to numbers
.map(i => {
return typeof i === "number"
? i + 1
: i;
})
// split letters and numbers up
.reduce((all, i) => {
typeof i === "string"
? all.letters.push(i)
: all.numbers.push(i);
return all;
}, { "letters": [], "numbers": [] });
// => { letters: ["A", "B", "C"], numbers: [2, 3, 4] }
- Veedrac 9y agoOr... you can do all of that in a 4-line loop, without any of the harm to readability or additional code-bloat that's especially important for websites.
- moosingin3space 9y agoThe problem with this is that it generates two intermediate arrays in the maps, then effectively drops them in the reduce. This may be inefficient. I wish that JavaScript's map/filter/reduce functions returned lazy iterators, like in Rust, so that code like this doesn't produce intermediate arrays. Does anyone know of a library that provides this?
- marmart 9y agoThose intermediate iterations could be dropped by composing the map functions together (same with the reduce), if that really was a performance bottleneck.
- moosingin3space 9y agoWith lazy iterators, there is the possibility of better composition of maps/filters/reduces. That's why I'm a fan of the lazy iterators approach -- otherwise the abstraction breaks too easily and it ends up looking like a for-loop anyway.