Merge

I put a lot of effort into avoiding mutation in my code and as such spend a heap of time typing const new = Object.assign({}, original, {changed}). In fact, in a recent project I wrote that 51 times.

However, it always felt like a bit of a hack having to supply the first argument as an empty object so it didn’t mutate the original. I mentioned this to a friend and they showed me a tiny, neat function that relies on ES6’s spread syntax:

const merge = (...xs) => Object.assign({}, ...xs)

This meant I could now write const new = merge(original, {changed}) instead, which seemed pretty neat until we thought about it a little and realised that all this time I could’ve just been writing const new = {...original, changed} instead…

Thanks for reading part two of my ongoing series on overthinking problems!