-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merger.ts
79 lines (62 loc) · 1.54 KB
/
Merger.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
72
73
74
75
76
77
78
79
export class Merger {
constructor(
public target: any[] | Record<string, any>,
public source: any[] | Record<string, any>,
public removeExisting: boolean
) {}
public merge() {
const target = this.target
const source = this.source
const isTargetArray = Array.isArray(target)
const isSourceArray = Array.isArray(source)
this.handleReplace(target)
if (isTargetArray && isSourceArray) {
this.mergeArray(target, source)
return
}
if (isTargetArray && !isSourceArray) {
this.mergeObjectIntoArray(target, source)
return
}
if (!isTargetArray && isSourceArray) {
this.mergeArrayIntoObject(target, source)
return
}
this.mergeObjects(target, source)
}
public static merge(
target: any[] | Record<string, any>,
source: any[] | Record<string, any>,
removeExisting = false
) {
const merger = new Merger(target, source, removeExisting)
merger.merge()
}
private handleReplace(target: any[] | Record<string, any>) {
if (!this.removeExisting) {
return
}
if (Array.isArray(target)) {
target.length = 0
return
}
for (const key in target) {
delete target[key]
}
}
private mergeArray(target: any[], source: any[]) {
target.push(...source)
}
private mergeObjects(
target: Record<string, any>,
source: Record<string, any>
) {
Object.assign(target, source)
}
private mergeObjectIntoArray(target: any[], source: Record<string, any>) {
target.push(source)
}
private mergeArrayIntoObject(target: Record<string, any>, source: any[]) {
Object.assign(target, source)
}
}