DEV Community

Cover image for Procedural Vs Functional way of solving a JS interview problem
pardeepr08
pardeepr08

Posted on

Procedural Vs Functional way of solving a JS interview problem

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 …

Top comments (0)