forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastDeepMerge.ts
More file actions
44 lines (41 loc) · 1.46 KB
/
Copy pathfastDeepMerge.ts
File metadata and controls
44 lines (41 loc) · 1.46 KB
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
/**
* Merges 2 objects without creating new object references
* The merged props will appear on the `target` object
* If `target` already has a value for a given key it will not be overwritten
*/
export const fastDeepMergeAndReplace = (
source: Record<any, any> | undefined | null,
target: Record<any, any> | undefined | null,
) => {
if (!source || !target) {
return;
}
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key) && source[key] !== null && typeof source[key] === `object`) {
if (target[key] === undefined) {
target[key] = new (Object.getPrototypeOf(source[key]).constructor)();
}
fastDeepMergeAndReplace(source[key], target[key]);
} else if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
};
export const fastDeepMergeAndKeep = (
source: Record<any, any> | undefined | null,
target: Record<any, any> | undefined | null,
) => {
if (!source || !target) {
return;
}
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key) && source[key] !== null && typeof source[key] === `object`) {
if (target[key] === undefined) {
target[key] = new (Object.getPrototypeOf(source[key]).constructor)();
}
fastDeepMergeAndKeep(source[key], target[key]);
} else if (Object.prototype.hasOwnProperty.call(source, key) && target[key] === undefined) {
target[key] = source[key];
}
}
};