mardi 14 avril 2020

What happens with the if statement when it's true?

I started with HackerRank and I'm a bloody beginner.

So I've a question to this code:

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}
/*
 * Create the function factorial here
 */
function factorial(n) {
    if (n === 1) {
        return 1
    } else {
        return n * factorial(n - 1)
    }
    return n;
}

function main() {
    const n = +(readLine());

    console.log(factorial(n));
}

I broke it down to something like this:

Let's depend n = 4;

4 === 1 ? // NO!
THEN:
4 * factorial(4-1) // n = 3;

3 === 1? // NO!
THEN:
3 * factorial(3-1) // n = 2;

2 === 1? // NO!
THEN:
2 * factorial(2-1) // n = 1;

1 === 1? // YES!
return 1;

What happens NOW? What happen with return 1 and what happend with all the other "loops"?! And why does it loop over and over, even when there is no loop?

Please try to explain as easy as possible.

Aucun commentaire:

Enregistrer un commentaire