I would like to know why part of this code works by doing what I hope is counting the number of times the part that calculates persistence is executed in the if (I am not sure if it is called that in Spanish or is the term real):
let contar = 0;
persistence = (param) => {
contar = 0;
if (param !== undefined && param > 0) {
let num = param;
let numString = num.toString();
let arreglo = numString.split("");
let arregloNum = arreglo.map(Number);
if (arregloNum.length >= 2) {
let calc = arregloNum.reduce((p, c) => p * c);
persistence(calc);
contar++;
console.log(calc);
return contar;
} else {
return 0;
}
} else {
return false;
}
};
console.log(persistence(39));
console.log(persistence(4));
console.log(persistence(25));
console.log(persistence(999));
But if I put contar++
before persistence(calc);
the counter it stays at 0. Here the code how it doesn't work correctly:
let contar = 0;
persistence = (param) => {
contar = 0;
if (param !== undefined && param > 0) {
let num = param;
let numString = num.toString();
let arreglo = numString.split("");
let arregloNum = arreglo.map(Number);
if (arregloNum.length >= 2) {
let calc = arregloNum.reduce((p, c) => p * c);
contar++;
persistence(calc);
console.log(calc);
return contar;
} else {
return 0;
}
} else {
return false;
}
};
console.log(persistence(39));
console.log(persistence(4));
console.log(persistence(25));
console.log(persistence(999));
Can someone explain to me what is causing this? Thank you
Well, I'm going to explain the execution sequence of your functions, I hope this helps you (the manual debug can be found in the code comments at the end, please read them):
We will now run your second algorithm manually as follows.
So what happened? well the only thing you are doing wrong is handling the global variable
contar
.Now so that you declare it
contar
as a global variable if you are going to use it as a local variable (since you always initialize it when entering the functionpesistence
) now if you want to keep the appropriate value of the counter, it is best to send it as a parameter of the function.You have to be careful when using global variables , you are expecting a certain value of that variablebut that has already been modified by another function after the main function has already made its changes so you already have a "garbage" value in that variable, I think this can enter into the issue of semaphores when accessing the same shared resource, in In this case, your shared resource is the variable
contar
, mmmmm, well, maybe the topic is something else, but I hope I have helped you clarify your doubt, good luck.Then your function could look like this if you decide to pass the counter as part of a parameter, where by default we set the counter to 0 when we don't send the parameter, so we continue calling
persistence(39)
will give you a counter initialized to 0 (contar
) by default as the second parameter, which we will then be sent to subsequent function callspersistence