Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

Commit

Permalink
Create contains.js in Javascript/src/recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
AJ-droi authored May 17, 2024
1 parent d3c2184 commit 6e80e97
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions algorithms/JavaScript/src/recursion/contains.js
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;
};

0 comments on commit 6e80e97

Please sign in to comment.