-
-
Save dmoney/6836237 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// my solution to exercise 5 of "you can't javascript under pressure" | |
// 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; | |
var counter = 0; | |
var stack = []; | |
var call=false; | |
var retval = null; | |
stack.push({'counter':counter, 'i': i, 'sum': 0}); | |
while (stack.length > 0){ | |
// pop the current state off the stack | |
var state = stack.pop(); | |
sum = state['sum']; | |
counter=state['counter']; | |
i=state['i']; | |
// if we're returning from a function call.. | |
if (retval !== null){ | |
sum += retval; | |
retval = null; | |
} | |
var idx = 0; | |
while (counter < i.length){ | |
idx = counter++; | |
if (typeof(i[idx]) =='number'){ | |
sum += i[idx]; | |
} | |
else if (typeof(i[idx]) == 'object'){ | |
// push current state onto stack before jumping to function | |
stack.push({'counter':counter, 'i': i, 'sum': sum}); | |
call=true; | |
break; | |
} | |
} | |
if (call){ | |
call=false; | |
// push parameters of the function call onto the stack | |
stack.push({'counter':0, 'i': i[idx], 'sum': 0}) | |
} | |
else { | |
retval = sum; | |
} | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment