DEV Community

loading...

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

Collapse
thepeoplesbourgeois profile image
Josh

I want union of any number of arrays, not just two. Any ideas how to refactor it still using the spread operator?

function union(a, ...b) {
  b.reduce((b, a) => [...a, ...b], a)
}
Enter fullscreen mode Exit fullscreen mode

Granted, the spread operator being used in the returned array like this means you'll be generating copies upon copies upon copies, but you asked for an arity-agnostic refactor, not a performant one 😜

Collapse
eecolor profile image
EECOLOR

Note that your ordering is a bit weird. You could do this (swap b and a in the reduce):

function union(...arrays) {
  return arrays.reduce((result, x) => [...result, ...x], [])
}
Enter fullscreen mode Exit fullscreen mode
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.

Collapse
paulsmithkc profile image
Paul Smith

This instantiates n+1 new arrays (where n is the number of arrays), when you could have just used a for loop to instantiate 1 new array.

Thread Thread
eecolor profile image
EECOLOR

Did you read the comment of @josh to which I replied?

Granted, the spread operator being used in the returned array like this means you'll be generating copies upon copies upon copies, but you asked for an arity-agnostic refactor, not a performant one 😜