The task is to implement _.get().
The boilerplate code
function get(source, path, defaultValue = undefined) {
// your code here
}
_.get() is a handy method for retrieving data from an arbitrary object.
source is the Object being read. path is where to look. defaultValue is where to return to if lookup fails.
If the source does not exist, return the value
if(source === null) return defaultValue;
If the path is empty or invalid, return the default value
if(path === null || (Array.isArray(path) && path.length === 0) || path === '') {
return defaultValue;
}
Normalise the path
const pathArray = Array.isArray(path)
? path
: path
.replace(/\[(\w+)\]/g, '.$1')
.replace(/^\./, '')
.split('.');
Traverse the object one key at a time
let result = source;
for (let key of pathArray) {
If the property cannot be read or the property does not exist, return the default value
if (result === null || !(key in result)) {
return defaultValue;
}
Update the result to the next nested value
result = result[key];
Return the final value
return result
The final code
function get(source, path, defaultValue = undefined) {
// your code here
if(source === null) return defaultValue;
if(path === null || (Array.isArray(path) && path.length === 0) || path === '') {
return defaultValue;
}
const pathArray = Array.isArray(path) ? path
: path
.replace(/\[(\w+)\]/g, '.$1')
.replace(/^\./, '')
.split('.');
let result = source;
for(let key of pathArray) {
if(result === null || !(key in result)) {
return defaultValue;
}
result = result[key];
}
return result;
}
That's all folks!
Top comments (0)