Created
December 3, 2022 17:01
-
-
Save MohdSaifulM/b9245d641c0154d24dc3999a5f1736ef to your computer and use it in GitHub Desktop.
Algorithms - Recursion
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
function nestedEvenSum (input) { | |
let sum = 0; | |
// Helper function to iterate through objects | |
function iterateInnerObject (input) { | |
for (let x in input) { | |
// If value is number and even add to sum | |
if (typeof(input[x]) === 'number' && input[x] % 2 === 0) sum += input[x]; | |
// If valus is object re run function | |
else if (typeof(input[x]) === 'object') iterateInnerObject(input[x]) | |
} | |
} | |
iterateInnerObject(input); | |
return sum; | |
} | |
var obj1 = { | |
outer: 2, | |
obj: { | |
inner: 2, | |
otherObj: { | |
superInner: 2, | |
notANumber: true, | |
alsoNotANumber: "yup" | |
} | |
} | |
} | |
var 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'} | |
}; | |
nestedEvenSum(obj1); // 6 | |
nestedEvenSum(obj2); // 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment