Skip to content

Instantly share code, notes, and snippets.

@MohdSaifulM
Created December 3, 2022 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohdSaifulM/b9245d641c0154d24dc3999a5f1736ef to your computer and use it in GitHub Desktop.
Save MohdSaifulM/b9245d641c0154d24dc3999a5f1736ef to your computer and use it in GitHub Desktop.
Algorithms - Recursion
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