Get by path
Implement getPath(object, path, fallback). path is a string such as a.b[0].c. Return the value at that path. Return fallback when a step is missing or when the value is undefined. A null, 0, false or empty string that exists is returned as it is.
Start from
function getPath(object, path, fallback) {
// Walk the path; return fallback when a step is missing.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Turn the path into a list of keys first: [0] becomes .0, then split on the dot.
Hint 2
Before each step, stop when the current value is null or undefined. After the last step, only undefined gives the fallback.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function getPath(object, path, fallback) {
const keys = path.replace(/\[(\w+)\]/g, ".$1").split(".").filter(Boolean);
let value = object;
for (const key of keys) {
if (value == null) return fallback;
value = value[key];
}
return value === undefined ? fallback : value;
}What an interviewer looks for
It is lodash get, a common warm-up. The scoring is in the edge cases: null in the middle of the path, and falsy values that must not turn into the fallback.