Merge a value at a nested path with copy-on-write
State libraries such as Redux treat state as immutable: an update returns a new state object, and React re-renders only the parts whose reference changed. Implement mergeAtPath(state, path, value), which returns a new state with value merged in at path, without touching the original.
mergeAtPath(state, path, value) // => new state
state is a plain object or an array. path is an array of keys: strings for object keys and numbers for array indexes.
state or anything inside it.state.null, a Date, …), replace it with a new empty container: an array if the next key is a number, otherwise a plain object.A plain object is an object whose prototype is Object.prototype or null.
Let current be the value at the end of the path (the root itself when path is empty).
current and value are both plain objects, the result is a new object with the keys of current and then the keys of value (value wins). This merge is shallow: nested objects inside value replace those in current.current followed by the elements of value.value replaces current and is stored as is (by reference).If any key in path is '__proto__', 'constructor', or 'prototype', return state itself and change nothing. This keeps paths built from user input from reaching shared prototypes.
const state = {
user: { profile: { name: 'Ada' }, prefs: { theme: 'dark' } },
posts: [{ id: 1, tags: ['js'] }],
};
const a = mergeAtPath(state, ['user', 'prefs'], { fontSize: 14 });
// a.user.prefs => { theme: 'dark', fontSize: 14 }
// a.user.profile === state.user.profile (shared)
// a.posts === state.posts (shared)
// state.user.prefs => { theme: 'dark' } (unchanged)
mergeAtPath(state, ['posts', 0, 'tags'], ['react']).posts[0].tags;
// => ['js', 'react']
mergeAtPath(state, ['user', 'profile', 'name'], 'Grace').user.profile;
// => { name: 'Grace' }
mergeAtPath({}, ['drafts', 0, 'title'], 'Hello');
// => { drafts: [{ title: 'Hello' }] }
mergeAtPath({ a: 1 }, [], { b: 2 });
// => { a: 1, b: 2 } (a new object)
mergeAtPath(state, ['__proto__', 'isAdmin'], true) === state;
// => true