Recursive function returning Undefined in Javascript with Node

Asked

Viewed 143 times

0

The recursive function below stops running when it arrives at "if (Sorted) " and the condition is true, as it should. Only it doesn’t matter what I put in to return, she doesn’t return.

If I do Return 1, it returns Undefined for example. There’s no logic to it

OBS: I already gave console.log in the variable "Sorted", it contains the boolean true.

Am I obligated to have a Return on an Else too? But it does not work, because the Sorted in the first call of the function, is false, then it already enters in the Else and for everything.

The code is being written on the Hackerhank platform. Main and inputs and outputs are already configured.

function minimumSwaps(arr, cont) {
    let sorted = arr.every(isAlreadySorted)
    if (sorted) return 1 
......
.....
..
}

And there on the Main function:

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine(), 10);

    const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));

    var cont = 0
    const res = minimumSwaps(arr, cont);


    ws.write(res + '\n');

    ws.end();
}

minimumSwaps returns Undefined. And then, the res printed on the screen is Undefined

  • 2

    Hi Lucas, can you create an example with the problem that can be run here? as well as code is missing to identify the problem...

1 answer

0

The point is that apparently Javascript on Node does not let a function have Return only on if and not Else.

The function worked correctly when I put the recursive call as Return of Else of if return:

function minimumSwaps(arr, cont) {
....
....
...

    let sorted = arr.every(isAlreadySorted)
    if (sorted) return 1 
    else return minimumSwaps(arr, cont)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.