Skip to content

Instantly share code, notes, and snippets.

@Jamie0
Created February 8, 2023 15:34
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 Jamie0/37c762b859a9b371858066efaeb9a3f5 to your computer and use it in GitHub Desktop.
Save Jamie0/37c762b859a9b371858066efaeb9a3f5 to your computer and use it in GitHub Desktop.
deepMerge.js
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