This repository has been archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 790
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create contains.js in Javascript/src/recursion
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
//Write a function called `contains` that searches for a value in a nested object. It returns true if the object contains that value. | ||
|
||
```javascript | ||
var nestedObject = { | ||
data: { | ||
info: { | ||
stuff: { | ||
thing: { | ||
moreStuff: { | ||
magicNumber: 44 | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
contains(nestedObject, 44) // true | ||
contains(nestedObject, "foo") // false | ||
``` | ||
|
||
// Solution | ||
const contains = (object, checkValue) => { | ||
if (object == null || Object.keys(object).length === 0) { | ||
return false; | ||
} | ||
|
||
for (let [key, value] of Object.entries(object)) { | ||
if (key === checkValue || value === checkValue) { | ||
return true; | ||
} | ||
if (typeof value === 'object' && contains(value, checkValue)) { | ||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
}; |