hiester
hiester

Reputation: 208

Why doesn't this recursive javascript function return the correct value

Why does this function return undefined?

The interior function returns the correct value.

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.

    (function (s, y) {
        if (!y || y.length < 1) {
            //console.log(s);
            // s is the correct value
            return s;
        } else {
            arguments.callee(s + y[0], y.slice(1));
        }
    })(0, i);
}

var x = [1, 2, 3, 4, 5];
arraySum(x);

Upvotes: 2

Views: 368

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

If what you said in the code's comment is true, this is what you need.

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.

    return (function (s, y) {
        if (y instanceof Array && y.length !== 0) {
            return arguments.callee(arguments.callee(s, y[0]), y.slice(1));
        } else if (typeof y === 'number') {
            return s + y;
        } else {
            return s;
        }
    })(0, i);
}

Output

var x = [1, 2, 3, 4, 5];
console.log(arraySum(x));
x = [1, 2, [3, 4, 5]];
console.log(arraySum(x));
x = [1, "2", 2, [3, 4, 5]];
console.log(arraySum(x));
x = [1, "2", [2, [3, 4, 5]]];
console.log(arraySum(x));

Upvotes: 0

chubbsondubs
chubbsondubs

Reputation: 38676

Change it to

return arguments.callee( s + y[0], y.slice(1))

Or just use reduce :-) :

[1,2,3,4].reduce( function(sum, x) { return sum + x; }, 0 );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 1

Related Questions