Procedural Vs Functional way of solving a JS interview problem

pardeepr08 - Aug 5 '23 - - Dev Community

Are you also stuck clearing the UI interviews 😕, don’t worry i have a problem for you to practise and learn 😎

💡Problem

Write a method called readKey that can access nested properties of an object using a given path.

Some use case for better understanding the problem

const obj = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3
    }
  }
}
console.log(readKey(obj, 'a')); // Output: 1
console.log(readKey(obj, 'b.c')); // Output: 2
console.log(readKey(obj, 'b.d.e')); // Output: 3
console.log(readKey(obj, 'x.y.z')); // Output: undefined (Property not found)
Enter fullscreen mode Exit fullscreen mode

Here’s how i thought of implementing the same using two approaches:

Procedural code 😕

function readKey(obj, path) {
  const keys = path.split('.');
  let result = obj;
  for (const key of keys) {
    if (typeof result === 'object' && result !== null) {
      result = result[key];
    } else {
      return undefined; // Property not found
    }
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Functional code 😎

function readKey(obj, path) {
  return path
    .split('.')
    .reduce((acc, key) => {
      if (acc !== null && typeof acc === 'object') {
        return acc[key]
      }
    }, obj)
}
Enter fullscreen mode Exit fullscreen mode

✋ Ignoring some edge cases in code for the sake of simplicity only.

Now, comparing both the approaches pros and cons 🤷‍♂️

To me functional approach is clean, short, abstract and more descriptive. Also shorter the code, less is the surface area for bugs 😁

On the other side, one can argue that procedural code is more optimized as we cannot break from reduce method when we are sure of not finding the key path in object 🤔 but still i trade that off with code readability 😎

What is your opinion on this 🤔 ? Please comment.

If you found this post relevant and worth read, follow me for more …

. . .
Terabox Video Player