Skip to content

Commit 6550c23

Browse files
committed
feat(helpers/mergedeep): updates the mergeDeep logic to make deep copy as well
#443
1 parent 40ba142 commit 6550c23

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/lib/helpers/mergeDeep.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,28 @@ export function isObject(item: unknown) {
1212
}
1313

1414
/**
15-
* Deep merge two objects.
15+
* Deep merge two objects with deep copy of the target object.
1616
* @param target
1717
* @param ...sources
1818
*/
1919
export function mergeDeep<T extends Record<string, unknown>>(target: T, ...sources: DeepPartial<T>[]): T {
2020
if (!sources.length) return target;
2121
const source = sources.shift();
22+
const output = { ...target };
2223

2324
if (isObject(target) && isObject(source)) {
2425
for (const key in source) {
2526
if (isObject(source[key])) {
26-
if (!target[key]) Object.assign(target, { [key]: {} });
27-
mergeDeep(target[key] as Record<string, unknown>, source[key] as Record<string, unknown>);
27+
if (!target[key]) Object.assign(output, { [key]: {} });
28+
(output[key] as Record<string, unknown>) = mergeDeep(
29+
target[key] as Record<string, unknown>,
30+
source[key] as Record<string, unknown>,
31+
);
2832
} else {
29-
Object.assign(target, { [key]: source[key] });
33+
Object.assign(output, { [key]: source[key] });
3034
}
3135
}
3236
}
3337

34-
return mergeDeep(target, ...sources);
38+
return mergeDeep(output, ...sources);
3539
}

0 commit comments

Comments
 (0)