|
| 1 | +Deep-Merge Two Nested Objects (with Circular References) |
| 2 | +Challenge: |
| 3 | +Implement a deep-merge function that combines two nested JavaScript objects while safely handling circular references. The function must be immutable and able to merge objects, arrays, and nested structures. |
| 4 | + |
| 5 | +Problem Description: |
| 6 | +Deep merging means recursively combining the properties of two objects. When both inputs contain nested objects, arrays, or shared references, this becomes more complex. |
| 7 | + |
| 8 | +Your task is to: |
| 9 | +Merge all properties from both objects |
| 10 | +Recursively merge nested objects |
| 11 | +Merge arrays by index |
| 12 | +Avoid infinite recursion when circular references exist |
| 13 | +Return a new, immutable object |
| 14 | +Ensure values from the second object override the first when conflicts occur |
| 15 | +Real-World Use Case |
| 16 | +State management libraries (Redux, Zustand, Immer) |
| 17 | +Complex configuration merging |
| 18 | +Deep cloning with overrides |
| 19 | +Normalizing API responses |
| 20 | +Merging schema definitions |
| 21 | + |
| 22 | +Example: |
| 23 | +Input |
| 24 | +const a = { |
| 25 | + x: 1, |
| 26 | + y: { z: 2 } |
| 27 | +}; |
| 28 | +a.self = a; // circular reference |
| 29 | + |
| 30 | +const b = { |
| 31 | + y: { k: 20 }, |
| 32 | + m: 100 |
| 33 | +}; |
| 34 | +b.loop = b; // circular reference |
| 35 | + |
| 36 | +const result = deepMerge(a, b); |
| 37 | + |
| 38 | +Output |
| 39 | +{ |
| 40 | + x: 1, |
| 41 | + y: { z: 2, k: 20 }, |
| 42 | + m: 100, |
| 43 | + self: [circular], |
| 44 | + loop: [circular] |
| 45 | +} |
| 46 | + |
| 47 | +Requirements: |
| 48 | +Must deep-merge nested objects and arrays |
| 49 | +Must detect and safely handle circular references |
| 50 | +Must not mutate inputs |
| 51 | +When both objects contain the same key: |
| 52 | +If both values are objects → recursively merge |
| 53 | +If both are arrays → merge by index |
| 54 | +Otherwise → value from second object overrides |
| 55 | +Must create a brand-new object as the output |
| 56 | + |
| 57 | +Key Concepts: |
| 58 | +Recursion |
| 59 | +WeakMap to track visited nodes |
| 60 | +Object and array cloning |
| 61 | +Circular reference detection |
| 62 | +Immutability principles |
0 commit comments