Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Created October 7, 2013 17:25
Show Gist options
  • Save simonewebdesign/6871624 to your computer and use it in GitHub Desktop.
Save simonewebdesign/6871624 to your computer and use it in GitHub Desktop.
"You Can't JavaScript Under Pressure" - LEVEL 5 - Closures + Recursion FTW! - http://toys.usvsth3m.com/javascript-under-pressure/
function arraySum(i) {
// i will be an array, containing integers, strings and/or arrays like itself.
// Sum all the integers you find, anywhere in the nest of arrays.
var sum = 0;
function maybeSum(x) {
if (typeof x === 'number') {
sum += parseInt(x);
} else if (Array.isArray(x)) {
for (var j=0; j<x.length; j++) {
maybeSum(x[j]);
}
}
}
// main cycle
for (var k=0; k<i.length; k++) {
maybeSum(i[k]);
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment