Skip to content

Instantly share code, notes, and snippets.

@artalar
Created April 9, 2018 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/a2e351c8f235cbf5642bd65f10b76150 to your computer and use it in GitHub Desktop.
Save artalar/a2e351c8f235cbf5642bd65f10b76150 to your computer and use it in GitHub Desktop.
const isObject = o => typeof o === 'object' && o !== null;
const merge = (source, key, update) =>
Array.isArray(source)
? [...source.slice(0, key > 0 ? key - 1 : 0), update, ...source.slice(key + 1)]
: { ...source, [key]: update };
const mergeIn = (source, target, update) =>
source === target
? Array.isArray(source) ? update : { ...source, ...update }
: Object.keys(source).reduce((acc, key) => {
const value = source[key];
if (value === target) return merge(source, key, value);
if (isObject(value)) return mergeIn(value, target, update);
return source;
}, source);
// TODO: `changeIn(source, target, field, value)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment