Background

Array.with() - Intent Over Implementation

A cleaner way to replace items in arrays that communicates what, not how

I recently stumbled upon a neat JavaScript method: Array.with().

It creates a new array with one item replaced. Shorter to write, but more importantly - easier to understand.

Its design clearly communicates what will happen, not how it's implemented. That's a big difference compared to manual array copying with the spread operator.

Nice. Simple. Useful.


Before

case "CLEAR_FIELD": {
  const next = [...state]
  const item = next[action.bookingIndex]
 
  next[action.bookingIndex] = {
    ...item,
    [action.fieldName]: null,
  }
 
  return next
}

After

case "CLEAR_FIELD": {
  const item = state[action.bookingIndex]
 
  return state.with(action.bookingIndex, {
    ...item,
    [action.fieldName]: null,
  })
}

I came across it while Cursor was suggesting a cleaner way to write a reducer.

Comments