I would like to add to that reduce is very good with binary operations that are closed under one type. Like "add" where you have (Number, Number) -> Number. The kind of functions where you don't even care who is an accumulator and what's the current value. You just plug it like this arr.reduce(binary_op) and you're done.
yes, summing two numbers is a classical example for reduce. It's actually reasonable because it really "reduces" the input into one value. I still prefer to use a util function for readability, like sum(numbers). Can be taken from lodash, but can also be just my own util that implements it with reduce. The name alone is worth the abstraction that I don't have to read reduce a bunch of times and have to grasp the implementation :)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I would like to add to that
reduce
is very good with binary operations that are closed under one type. Like "add" where you have(Number, Number) -> Number
. The kind of functions where you don't even care who is an accumulator and what's the current value. You just plug it like thisarr.reduce(binary_op)
and you're done.yes, summing two numbers is a classical example for reduce. It's actually reasonable because it really "reduces" the input into one value. I still prefer to use a util function for readability, like
sum(numbers)
. Can be taken from lodash, but can also be just my own util that implements it with reduce. The name alone is worth the abstraction that I don't have to readreduce
a bunch of times and have to grasp the implementation :)