Created
August 18, 2020 17:46
-
-
Save valorad/ccab256462f5cc89ed76792d0f10d0c9 to your computer and use it in GitHub Desktop.
Deep Merge TypeScript
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
const isObject = (obj: any) => obj && typeof obj === 'object'; | |
const deepMergeInner = (target: any, source: any) => { | |
Object.keys(source).forEach((key: string) => { | |
const targetValue = target[key]; | |
const sourceValue = source[key]; | |
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { | |
target[key] = targetValue.concat(sourceValue); | |
} else if (isObject(targetValue) && isObject(sourceValue)) { | |
target[key] = deepMergeInner(Object.assign({}, targetValue), sourceValue); | |
} else { | |
target[key] = sourceValue; | |
} | |
}); | |
return target; | |
} | |
export default (...objects: object[]) => { | |
if (objects.length < 2) { | |
throw new Error(`DeepMerge: This function expects at least 2 objects to be provided`); | |
} | |
if (objects.some(object => !isObject(object))) { | |
throw new Error(`DeepMerge: All values should be of type "object"`); | |
} | |
return objects.reduce((prev, current) => { | |
return deepMergeInner(prev, current) | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment