0

I'm doing a problem on LeetCode and for some reason my function keeps returning undefined. I'm basically just running a recursive function and then keeping track of the results, and eventually returning them in the main function largestNumber in the variable endRes.

/**
 * @param {number[]} nums
 * @return {string}
 */

function recursion(arr, str) {
    var result = str; 
    if (arr.length <= 1) {
        result+=arr[0];
        return result;
    }
    arr.sort(function(a, b){return b-a});
    var n = arr[0];
    var power = Math.floor(Math.log(n)/Math.LN10);
    for (var i=1; i<arr.length; i++) {
        var index;
        if (arr[i]>(arr[0]/(Math.pow(10, power))) && Math.floor(Math.log(arr[i])/Math.LN10) < power) {
            result+=arr[i].toString();
            arr.splice(i,1);
            recursion(arr, result);
        }
        if (i==arr.length-1){
            result+=arr[0].toString();
            arr.splice(0,1);
            recursion(arr, result);
        }
    }
}

var largestNumber = function(nums) {
    endRes = recursion(nums, "");
    return endRes;
};
vercingortix
  • 199
  • 2
  • 15
  • 9
    You aren't returning your recursive functions. ie `recursion(arr, result);` should be `return recursion(arr, result);` – shamsup May 26 '16 at 19:13
  • Dang bud! That was it. Can I ask you why you can't just call the function? Why do you need the return there? (Sorry I'm new). – vercingortix May 26 '16 at 19:16
  • 1
    Javascript doesn't have implicit returns like ruby does. You have to declare them explicitly. – shamsup May 26 '16 at 19:17

1 Answers1

0

Inside of your recursion() function, you aren't returning your recursive calls.

for (var i=1; i<arr.length; i++) {
    var index;
    if (arr[i]>(arr[0]/(Math.pow(10, power))) && Math.floor(Math.log(arr[i])/Math.LN10) < power) {
        result+=arr[i].toString();
        arr.splice(i,1);
        return recursion(arr, result); // add return here
    }
    if (i==arr.length-1){
        result+=arr[0].toString();
        arr.splice(0,1);
        return recursion(arr, result); // add return here
    }
}
shamsup
  • 1,952
  • 14
  • 18