3

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?

2
  • 3
    What happens if you add return before the recursive call to tupleAdd()? Commented Nov 14, 2013 at 22:42
  • 1
    How about doing return tupleAdd(tuple, i, p, t, output) ? Commented Nov 14, 2013 at 22:43

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Upvoted you and Ben. I just accepted his because he was first to comment. I didn't have a better criteria, since both answers were equally helpful and came in at about the same time.
2

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);

Comments

-2
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}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.