Reputation: 3760
I was inspired by this question to write a recursive function in JavaScript to add elements of an array and return an array accordingly.
in Pseudocode
arr = [1,2,3,4,5,6]
func (arr,2) = > [1+3+5, 2+4+6]
[9,12]
func (arr,3) = > [1+4,2+5,3+6]
[5,7,9]
So I wrote a fiddle, here.
var input = [1,2,3,4,5,6,7,8,9];
function tupleAdd(tuple,i,p,t,output){
if(typeof t == "undefined")
t=0;
if(typeof p == "undefined")
p=0;
if(typeof output == "undefined")
output = [];
if(typeof output[t] =="undefined")
output[t]=0;
output[t]+=i[p];
p++;
t++;
t>=tuple?t=0:null;
if(p<i.length)
tupleAdd(tuple,i,p,t,output);
else{
console.log(output);
return(output);
}
}
x = tupleAdd(3,input);
console.log(x);
My function works, as the first console.log()
shows the appropriate values. What weirds me out is that when I return
output
(with or without parens), and try and log it again, I get undefined
.
I find this deeply unsettling. Can anyone shed some light on why the return
value is different than the console.log
value?
Upvotes: 3
Views: 424
Reputation: 897
function doTuple(arr, tuple){
if(!arr.length){
return tuple;
}
var el = arr.splice(0,1);
el % 2 ? tuple.evens += +el : tuple.ods += +el;
return doTuple(arr, tuple);
}
console.log(doTuple([1,2,3,4,5], {evens:0,ods:0}));
Upvotes: -2
Reputation: 53198
You need to return the value of the recursive call:
var input = [1,2,3,4,5,6,7,8,9];
function tupleAdd(tuple,i,p,t,output){
if(typeof t == "undefined")
t=0;
if(typeof p == "undefined")
p=0;
if(typeof output == "undefined")
output = [];
if(typeof output[t] =="undefined")
output[t]=0;
output[t]+=i[p];
p++;
t++;
t>=tuple?t=0:null;
if(p<i.length)
return tupleAdd(tuple,i,p,t,output);
else{
console.log(output);
return(output);
}
}
x = tupleAdd(3,input);
console.log(x);
Upvotes: 2
Reputation: 207501
Your recursion is broken. You are getting undefined since you do not have a return on the function call inside.
tupleAdd(tuple,i,p,t,output);
needs to be
return tupleAdd(tuple,i,p,t,output);
Upvotes: 3