Created
April 9, 2018 22:46
-
-
Save artalar/a2e351c8f235cbf5642bd65f10b76150 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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