I solved kata on codewars. Acctually I did this by accident and I don’t understand why this code works. May you explain it?
Kata:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
39 –> 3 (because 39 = 27, 27 = 14, 1*4 = 4 and 4 has only one digit)
My solution:
function persistence(num) {
let count = 0;
const arr = [...num.toString()];
const sumArr = arr.reduce((res, val) => (res *= val));
if (arr.length > 1) {
**// Why? How this line works?
// Why it doesn't crashes?
// Why it returns correct counter value and calls the function?**
count += 1 + persistence(sumArr)
}
return count;
}
persistence(39); //3
Why if I do like this, the counter do not save the result:
if (arr.length > 1) {
count += 1
persistence(sumArr) }