forked from NKaty/Algorithms-and-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnested-even-sum.js
39 lines (33 loc) · 849 Bytes
/
nested-even-sum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// nestedEvenSum
// Write a recursive function called nestedEvenSum.
// Return the sum of all even numbers in an object which may contain nested objects.
function nestedEvenSum(obj) {
let sum = 0;
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof obj[key] === 'number' && obj[key] % 2 === 0) sum += obj[key];
if (typeof obj[key] === 'object') sum += nestedEvenSum(obj[key]);
}
}
return sum;
}
const obj1 = {
outer: 2,
obj: {
inner: 2,
otherObj: {
superInner: 2,
notANumber: true,
alsoNotANumber: 'yup'
}
}
};
const obj2 = {
a: 2,
b: { b: 2, bb: { b: 3, bb: { b: 2 } } },
c: { c: { c: 2 }, cc: 'ball', ccc: 5 },
d: 1,
e: { e: { e: 2 }, ee: 'car' }
};
console.log(nestedEvenSum(obj1)); // 6
console.log(nestedEvenSum(obj2)); // 10