forked from typescript-eslint/typescript-eslint
/
deepMerge.ts
46 lines (41 loc) · 1.35 KB
/
deepMerge.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
type ObjectLike<T = any> = Record<string, T>;
/**
* Check if the variable contains an object stricly rejecting arrays
* @param obj an object
* @returns `true` if obj is an object
*/
export function isObjectNotArray<T extends object>(obj: T | any[]): obj is T {
return typeof obj === 'object' && !Array.isArray(obj);
}
/**
* Pure function - doesn't mutate either parameter!
* Merges two objects together deeply, overwriting the properties in first with the properties in second
* @param first The first object
* @param second The second object
* @returns a new object
*/
export function deepMerge(first: ObjectLike = {}, second: ObjectLike = {}) {
// get the unique set of keys across both objects
const keys = new Set(Object.keys(first).concat(Object.keys(second)));
return Array.from(keys).reduce(
(acc, key) => {
const firstHasKey = key in first;
const secondHasKey = key in second;
if (firstHasKey && secondHasKey) {
if (isObjectNotArray(first[key]) && isObjectNotArray(second[key])) {
// object type
acc[key] = deepMerge(first[key], second[key]);
} else {
// value type
acc[key] = second[key];
}
} else if (firstHasKey) {
acc[key] = first[key];
} else {
acc[key] = second[key];
}
return acc;
},
{} as ObjectLike,
);
}