Skip to content

Instantly share code, notes, and snippets.

Created October 5, 2013 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/6836227 to your computer and use it in GitHub Desktop.
Save anonymous/6836227 to your computer and use it in GitHub Desktop.
recursion implemented with while loops
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