Last active
March 2, 2023 23:16
-
-
Save havenchyk/052f82118a9f4149db0650208d9f3db3 to your computer and use it in GitHub Desktop.
deep 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
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