Created
February 8, 2023 15:34
-
-
Save Jamie0/37c762b859a9b371858066efaeb9a3f5 to your computer and use it in GitHub Desktop.
deepMerge.js
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
function deepMerge(a, b, path = []) { | |
if (typeof a != 'object') return b; | |
for (var key in b) { | |
if (b[key] === undefined) { | |
delete a[key]; | |
continue; | |
} | |
if ( | |
key in a && | |
key in b && | |
typeof a[key] != typeof b[key] && | |
a[key] !== null && | |
b[key] !== null | |
) { | |
throw new Error( | |
'Incompatible types: ' + | |
path.concat([key]).join('.') + | |
' expected ' + | |
typeof a[key] + | |
' got ' + | |
typeof b[key] | |
); | |
} | |
Object.assign(a, { | |
[key]: deepMerge( | |
key in a ? a[key] : b[key], | |
b[key], | |
path.concat([key]) | |
), | |
}); | |
} | |
return a; | |
} | |
module.exports = deepMerge; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment