The traditional solution is to pass the count as a parameter to the function as suggested by another answer.
However, there is another solution in js. A few other answers suggested simply declaring count outside the recursive function:
let counter = 0
function singleDigit(num) {
counter++;
// ..
}
This of course works. However this makes the function non-reentrant (cannot be called twice correctly). In some cases you can ignore this problem and simply make sure you don't call singleDigit
twice (javascript is single threaded so it's not too hard to do) but this is a bug waiting to happen if you update singleDigit
later to be asynchronous and it also feels ugly.
The solution is to declare the counter
variable outside but not globally. This is possible because javascript has closures:
function singleDigit(num) {
let counter = 0; // outside but in a closure
// use an inner function as the real recursive function:
function recursion (num) {
counter ++
let number = [...num + ''].map(Number).reduce((x, y) => {return x * y})
if(number <= 9){
return counter // return final count (terminate)
}else{
return recursion(number) // recurse!
}
}
return recursion(num); // start recursion
}
This is similar to the global solution but each time you call singleDigit
(which is now not a recursive function) it will create a new instance of the counter
variable.