Skip to content

Instantly share code, notes, and snippets.

@havenchyk
Last active March 2, 2023 23:16
Show Gist options
  • Save havenchyk/052f82118a9f4149db0650208d9f3db3 to your computer and use it in GitHub Desktop.
Save havenchyk/052f82118a9f4149db0650208d9f3db3 to your computer and use it in GitHub Desktop.
deep merge
function isPlainObject(item: unknown): item is Record<string, unknown> {
return item && (item as object).constructor === Object
}
function filterProto([key, value]: [string, unknown]) {
// Avoid prototype pollution
return key !== '__proto__'
}
const deepmerge = (
target: unknown,
source: unknown,
options = { clone: true }
) => {
if (!isPlainObject(target) || !isPlainObject(source)) {
console.warn('Please, make sure that objects are passed as parameters')
return {}
}
const output = options.clone ? { ...target } : target
// TODO: reduce complexity
Object.entries(source).filter(filterProto).forEach(([key, value]) => {
if (isPlainObject(value) && key in target) {
output[key] = deepmerge(target[key], value, options)
} else {
output[key] = value
}
})
return output
}
export { deepmerge }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment