Write a function `setIn(obj, path, value)` that returns a new object with the value set at the given dot-notation path, without mutating the original.
Problem Statement
Write a function `setIn(obj, path, value)` that returns a new object with the value set at the given dot-notation path, without mutating the original.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Create shallow copies at each level of the path.
š” Hint 2:
Split the path by "." and walk through, copying each level.
š” Hint 3:
Use reduceRight or iterate through path segments creating new objects at each step.
ā
Solution:
```javascript
function setIn(obj, path, value) {
const keys = path.split(".");
const result = { ...obj };
let current = result;
for (let i = 0; i < keys.length - 1; i++) {
current[keys[i]] = { ...current[keys[i]] };
current = current[keys[i]];
}
current[keys[keys.length - 1]] = value;
return result;
}
```