I'm writing a function which takes in a positive number and returns the number of times you must multiply the digits in num until you reach a single digit.
example:
test(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit//if single digit return num
The code:
function test(num) {
if (num > 10) { return num} else {
var j = num;var a;var count = 0;
while ( j > 10){
a = num.toString().split('').map( e=> parseInt(e)).reduce((a,c)=> a*c);
num = a;
count++;
j--;
}
return count;
}}
test(39) //outputs 29 expected 3;
I have fixed the above by adding an array and filtering for unique values but would still like to know why the code is giving me a much higher count than expected.
numis already below 10, shouldn't it return0and not the number itself? I mean you describe your function as returning the number of iterations, not a result from a calculation.j--part is the bit that's making the result far too high. You can addconsole.log(a,num,j)inside the while to see what it's doing (or step through with the debugger). Alsoreturn numat the start makes no sense, should bereturn 0as num<10 means it's already single digit so doesn't need to run your algorithm.