JS Built-ins
redux-legacysetInadvanced

Immutable Deep Update

πŸ“– Usage Example
const state = { user: { address: { city: 'Madrid' } } }
const next = setIn(state, ['user', 'address', 'city'], 'Barcelona')

next.user.address.city  // β†’ 'Barcelona'
state.user.address.city // β†’ 'Madrid'  (unchanged)

setIn eliminates boilerplate spread chains for deep updates while guaranteeing immutability at every level.

Immutable Deep Update

Updating deeply nested state immutably with spread operators can become verbose. A utility like setIn(obj, path, value) handles this recursively:

setIn(state, ['user', 'address', 'city'], 'Barcelona')
// β†’ { ...state, user: { ...state.user, address: { ...state.user.address, city: 'Barcelona' } } }

Challenge: Implement setIn(obj, path, value) that returns a new object with the value set at the given key path, without mutating the original at any level.

πŸ’‘ Hints (2)
  • β€’ Use recursion: when `path.length === 0` return `value`, otherwise go one level deeper.
  • β€’ `Object.assign({}, obj, { [key]: ... })` creates a shallow copy with the one key overridden.