@@ -6,38 +6,36 @@ Write a function **`deepMerge(objA, objB)`** that merges two JavaScript objects
66
77The function must follow these rules:
88
9- 1 . If a property exists in only one object, take that value.
10- 2 . If the property exists in both objects :
9+ 1 . If a property exists only in one object, return that value.
10+ 2 . If both objects contain the same key :
1111 - If both values are ** plain objects** , recursively merge them.
1212 - If both values are ** arrays** , concatenate them.
13- - Otherwise, the value from ** objB** overwrites the one from ** objA** .
14- 3 . Handle ** circular references** safely.
15- If you encounter the same reference path again, avoid infinite recursion.
16- 4 . Ensure the merge is ** immutable** — return a ** new** object.
17- 5 . Ensure the solution runs in ** O(n)** time where * n* is the total number of properties.
13+ - Otherwise, the value from ** objB** overwrites the value from ** objA** .
14+ 3 . Handle ** circular references** safely using a ` WeakMap ` to track already merged objects.
15+ 4 . The merge must be ** immutable** — return a ** new** object.
1816
1917---
2018
21- ### Example:
19+ ### Example
2220
2321``` js
24- const a = {
25- x: { y: 1 },
26- arr: [1 , 2 ],
22+ const firstObject = {
23+ x: { y: 1 },
24+ arr: [1 , 2 ],
2725};
28- a .self = a ; // Circular reference
26+ firstObject .self = firstObject ; // Circular reference
2927
30- const b = {
31- x: { z: 2 },
32- arr: [3 ],
33- extra: true
28+ const secondObject = {
29+ x: { z: 2 },
30+ arr: [3 ],
31+ extra: true ,
3432};
35- b .loop = b ; // Circular reference
33+ secondObject .loop = secondObject ; // Circular reference
3634
37- const result = deepMerge (a, b );
35+ const result = deepMerge (firstObject, secondObject );
3836
3937/*
40- Expected structure :
38+ Expected output :
4139
4240{
4341 x: { y: 1, z: 2 },
@@ -47,3 +45,4 @@ Expected structure:
4745 loop: <circular ref>
4846}
4947*/
48+
0 commit comments