-
-
Save jrson83/b0280e26395809f66897b52f4259ec55 to your computer and use it in GitHub Desktop.
deep merge
This file contains hidden or 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