Last active
July 7, 2025 18:31
-
-
Save JoshDevHub/b00125f483d4a1ecc257eaa030916973 to your computer and use it in GitHub Desktop.
Recursive Contains
This file contains hidden or 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unless I'm missing something, the given solution in the original post works with flat objects just fine @kazeneza-zephilin
Your solution is also more repetitive, effectively adding the exact same guard check twice. This might have some marginal performance gains by avoiding new stack frames in certain contexts, but I think it's unlikely to be meaningful.