-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.ts
71 lines (57 loc) · 1.76 KB
/
merge.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
interface IObject {
[key: string]: any;
length?: never;
}
type TUnionToIntersection<U> = (
U extends any ? (k: U) => void : never
) extends (k: infer I) => void
? I
: never;
// istanbul ignore next
const isObject = (obj: any) => {
if (typeof obj === "object" && obj !== null) {
if (typeof Object.getPrototypeOf === "function") {
const prototype = Object.getPrototypeOf(obj);
return prototype === Object.prototype || prototype === null;
}
return Object.prototype.toString.call(obj) === "[object Object]";
}
return false;
};
export const merge = <T extends IObject[]>(
...objects: T
): TUnionToIntersection<T[number]> =>
objects.reduce((result, current) => {
Object.keys(current).forEach((key) => {
if (Array.isArray(result[key]) && Array.isArray(current[key])) {
result[key] = merge.options.mergeArrays
? Array.from(new Set((result[key] as unknown[]).concat(current[key])))
: current[key];
} else if (isObject(result[key]) && isObject(current[key])) {
result[key] = merge(result[key] as IObject, current[key] as IObject);
} else {
result[key] = current[key];
}
});
return result;
}, {}) as any;
interface IOptions {
mergeArrays: boolean;
}
const defaultOptions: IOptions = {
mergeArrays: true,
};
merge.options = defaultOptions;
merge.withOptions = <T extends IObject[]>(
options: Partial<IOptions>,
...objects: T
) => {
merge.options = {
mergeArrays: true,
...options,
};
const result = merge(...objects);
merge.options = defaultOptions;
return result;
};
export default merge;