DEV Community

Discussion on: How to write IMMUTABLE code and never get stuck debugging again

Collapse
 
eecolor profile image
EECOLOR • Edited

Unless you are benchmarking and actively measuring performance, then you almost certainly shouldn’t care.

Yeah! The only situations I know I am using mutability is when I have to process tens of thousands of items, like this:

const index = array.reduce(
  (result, x) => (result[x.prop] = x, result),
  {}
)
Enter fullscreen mode Exit fullscreen mode

If it is below tens of thousands I will write this:

const index = array.reduce(
  (result, x) => ({ ...result, [x.prop]: x }),
  {}
)
Enter fullscreen mode Exit fullscreen mode

My rule is: if mutation makes the code significantly better to read or actually helps with performance, you can apply it locally.

So in code reviews I ask people to move stuff into functions that, from the outside, seem to be immutable:

function replaceAt(array, index, x) {
  const copy = array.slice()
  array[index] = x
  return copy
}
Enter fullscreen mode Exit fullscreen mode

The alternative would be something like this (more likely to have errors):

function replaceAt(array, index, x) {
  return [...array.slice(0, index), x, ...array.slice(index + 1)]
}
Enter fullscreen mode Exit fullscreen mode

Side note: if a language has an immutable construct in it's standard library I would prefer that.