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)
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;
}
Functional code π
function readKey(obj, path) {
return path
.split('.')
.reduce((acc, key) => {
if (acc !== null && typeof acc === 'object') {
return acc[key]
}
}, obj)
}
β 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)