DEV Community

Discussion on: 5 JavaScript "tips" that might bite you back.

Collapse
 
thepeoplesbourgeois profile image
Josh

Every single time I use reduce, I forget how whichever language I'm using it in organizes either its own arguments, or the arguments given to its lambda/block. 🤦‍♂️

Ruby:

init = 0
(1..10).reduce(init) do |accumulator, iteration| 
  accumulator + iteration  
end # 55
Enter fullscreen mode Exit fullscreen mode

Elixir:

init = 0
Enum.reduce(1..10, init, fn iteration, accumulator ->
  accumulator + iteration
end) # 55
Enter fullscreen mode Exit fullscreen mode

And now, (thank you,) Javascript:

function union(a, ...b) {
  return b.reduce((accumulator, iteration) => [...accumulator, ...iteration], a)
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
eecolor profile image
EECOLOR

Haha, yeah. In Scala you have foldLeft and foldRight, where foldLeft has it as the first argument and foldRight as the second argument.