Last active
July 6, 2024 04:26
-
-
Save JoshDevHub/b00125f483d4a1ecc257eaa030916973 to your computer and use it in GitHub Desktop.
Recursive Contains
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// solution to problem #6 in recursive exercises | |
function contains(object, searchValue) { | |
// because `null` has a typof "object", we have to explicitly check | |
// to prevent trying to access `null`'s values (which don't exist) | |
if (typeof object !== "object" || object === null) { | |
return object === searchValue; | |
} | |
for (const value of Object.values(object)) { | |
// An important problem in the code quiz solution is that `return contains()` will only | |
// search the first property of an object, as it will return whatever the result for it is. | |
// If our value was nested within the second property, for example, it would never get checked | |
// even if the first nested object did not contain it. | |
if (contains(value, searchValue)) { | |
return true; | |
} | |
} | |
return false; | |
} |
function nested(objeto, item) {
for (let key in objeto) {
if (objeto[key] === item) {
return true;
}
if (typeof objeto[key] === 'object') {
if (nested(objeto[key], item)) {
return true;
}
}
}
return false;
}
Can I get an iterative approach?
Just adding another recursive solution here that utilizes Array.prototype.some, nice and succinct:
function contains(obj, targetValue) {
if (typeof obj !== 'object' || obj === null) return false;
return Object.values(obj).some(
(value) => value === targetValue || contains(value, targetValue),
);
}
I had originally used a ternary statement (below) as the callback for .some(), which felt a bit easier to read to me, but for the sake of keeping it short, modified to the above.
function contains(obj, targetValue) {
if (typeof obj !== 'object' || obj === null) return false;
return Object.values(obj).some((value) =>
value === targetValue ? true : contains(value, targetValue),
);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@JoshDevHub Thanks for taking the time to review my code!
You're absolutely correct. I guess I was sleep deprived when I was writing that code because I can't believe that I missed these bugs 😅.