Write a function `deepMerge(target, source)` that deeply merges source into target. Arrays are replaced, objects are recursively merged.
Problem Statement
Write a function `deepMerge(target, source)` that deeply merges source into target. Arrays are replaced, objects are recursively merged.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
If both values are plain objects, merge recursively.
š” Hint 2:
If either is not an object, the source value wins.
š” Hint 3:
For each key in source, check if both target[key] and source[key] are objects, then recurse.
ā
Solution:
```javascript
function deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (typeof source[key] === "object" && source[key] !== null && !Array.isArray(source[key]) &&
typeof result[key] === "object" && result[key] !== null && !Array.isArray(result[key])) {
result[key] = deepMerge(result[key], source[key]);
} else {
result[key] = source[key];
}
}
return result;
}
```