Re:Javascript Arrays and Functional Programming
by guiomie on Thursday August 03, 2017 @09:46AM
(#14919505)
In his example Array.prototype.reduce, isn't this almost the same as just doing a foreach loop? I don't understand why doing this, it's pretty much the same number of lines.
[ Parent
| on HN ]
Re:Javascript Arrays and Functional Programming
by ablomen on Thursday August 03, 2017 @10:05AM
(#14919644)
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] }
Re:Javascript Arrays and Functional Programming
by moosingin3space on Thursday August 03, 2017 @03:05PM
(#14922688)
The 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?
Re:Javascript Arrays and Functional Programming
by marmart on Thursday August 03, 2017 @08:08PM
(#14925251)
Those intermediate iterations could be dropped by composing the map functions together (same with the reduce), if that really was a performance bottleneck.
Re:Javascript Arrays and Functional Programming
by moosingin3space on Sunday August 06, 2017 @08:40PM
(#14944543)
With 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.
Re:Javascript Arrays and Functional Programming
by Veedrac on Thursday August 03, 2017 @01:33PM
(#14921698)
Or... 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.
Re:Javascript Arrays and Functional Programming
by bestest on Thursday August 03, 2017 @10:11AM
(#14919711)
That's the thing about functional programming. I personally don't remember the last time I had the need to write a foreach loop. Foreach loops even kind of feel _dirty_ to me.
All I really need now is Array.map, Array.reduce, Array.filter, Array.sort, Object.keys, Object.values.
Reduce is very powerful, you just have to get to know it.
Edit: this is how I'd use reduce in this case — https://news.ycombinator.com/item?id=14919636 — talk about line numbers