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 -
Its design clearly communicates
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.
