Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Created May 2, 2022 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbyrne/1a40ffe83afd331281fa35f735776839 to your computer and use it in GitHub Desktop.
Save jasonbyrne/1a40ffe83afd331281fa35f735776839 to your computer and use it in GitHub Desktop.
Deep Merge and Shallow Merge
export const shallowMerge = <T extends object = Record<string, any>>(
...objects: T[]
): T => {
return objects.reduce((prev, cur) => ({ ...prev, ...cur }), {} as T);
};
export const deepMerge = <T extends object = Record<string, any>>(
target: T,
...sources: object[]
): T => {
const merge = (target: object, source: object) => {
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 (is.object(targetValue) && is.object(sourceValue)) {
target[key] = merge(Object.assign({}, targetValue), sourceValue);
} else {
target[key] = sourceValue;
}
});
return target;
};
return sources.reduce((prev, cur) => merge(prev, cur), target) as T;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment