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)