DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 113

The task is to implement _.get().

The boilerplate code

function get(source, path, defaultValue = undefined) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

_.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;
Enter fullscreen mode Exit fullscreen mode

If the path is empty or invalid, return the default value

if(path === null || (Array.isArray(path) && path.length === 0) || path === '') {
    return defaultValue;
  }
Enter fullscreen mode Exit fullscreen mode

Normalise the path

const pathArray = Array.isArray(path)
  ? path
  : path
      .replace(/\[(\w+)\]/g, '.$1')
      .replace(/^\./, '')
      .split('.');
Enter fullscreen mode Exit fullscreen mode

Traverse the object one key at a time

let result = source;

for (let key of pathArray) {
Enter fullscreen mode Exit fullscreen mode

If the property cannot be read or the property does not exist, return the default value

if (result === null || !(key in result)) {
  return defaultValue;
}
Enter fullscreen mode Exit fullscreen mode

Update the result to the next nested value

result = result[key];
Enter fullscreen mode Exit fullscreen mode

Return the final value

return result
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)