Skip to content

Commit 8a4a429

Browse files
feat: Add deep-merge nested objects exercise with circular reference handling
1 parent 09e31a5 commit 8a4a429

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Exercise: Deep-Merge Two Nested Objects With Circular References
2+
3+
### Problem Statement
4+
5+
Write a function **`deepMerge(objA, objB)`** that merges two JavaScript objects **without mutating** either of the original objects.
6+
7+
The function must follow these rules:
8+
9+
1. If a property exists in only one object, take that value.
10+
2. If the property exists in both objects:
11+
- If both values are **plain objects**, recursively merge them.
12+
- 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.
18+
19+
---
20+
21+
### Example:
22+
23+
```js
24+
const a = {
25+
x: { y: 1 },
26+
arr: [1, 2],
27+
};
28+
a.self = a; // Circular reference
29+
30+
const b = {
31+
x: { z: 2 },
32+
arr: [3],
33+
extra: true
34+
};
35+
b.loop = b; // Circular reference
36+
37+
const result = deepMerge(a, b);
38+
39+
/*
40+
Expected structure:
41+
42+
{
43+
x: { y: 1, z: 2 },
44+
arr: [1, 2, 3],
45+
extra: true,
46+
self: <circular ref>,
47+
loop: <circular ref>
48+
}
49+
*/

0 commit comments

Comments
 (0)