Write a function `getIn(obj, path, defaultVal)` that safely accesses a deeply nested property using a dot-notation path. Returns defaultVal if not found.
Problem Statement
Write a function `getIn(obj, path, defaultVal)` that safely accesses a deeply nested property using a dot-notation path. Returns defaultVal if not found.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Split the path by "." and traverse the object.
š” Hint 2:
If any intermediate value is null/undefined, return the default.
š” Hint 3:
Use reduce to walk through the path segments.
ā
Solution:
```javascript
function getIn(obj, path, defaultVal) {
const result = path.split(".").reduce((acc, key) => acc != null ? acc[key] : undefined, obj);
return result !== undefined ? result : defaultVal;
}
```