Created
December 20, 2022 04:13
-
-
Save kevinfiol/8d25ec09cdb838b62112fd3f09b764ac to your computer and use it in GitHub Desktop.
small immutable object merge
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
let NIL = void 0, | |
isObj = x => x && Object.getPrototypeOf(x) === Object.prototype; | |
function merge(obj, patch) { | |
obj = Array.isArray(obj) ? [ ...obj ] : isObj(obj) ? { ...obj } : NIL; | |
if (!obj) throw Error('You can only copy objects or arrays.'); | |
for (let k in patch) { | |
let v = patch[k]; | |
if (typeof v === 'function') obj[k] = v(obj[k]); | |
else if (isObj(v) && isObj(obj[k])) obj[k] = merge(obj[k], v); | |
else if (v === NIL) delete obj[k]; | |
else obj[k] = v; | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
multiple patches: