02-2 : Persistent Bugger

Recursion

Approach 1: Recursion + Helper Function

/*
Recursive helper function that returns the product result of multiplying the digits of a number together
>>> multiplyDigits(43) 
12
*/
function multiplyDigits(num){
  if (num <= 9){
    return num
  }
  else {
    return num % 10 * multiplyDigits(Math.floor(num / 10))
  }
}

/*
Recursive function that returns the count of the multiplicative persistence.
*/
function persistence(num) {
  if (num <= 9){
    return 0
  }
  else{
    return 1 + persistence(multiplyDigits(num))
  }
}

We can define a recursive helper function that will calculate the product of multiplying each digit in a number. In our primary recursive function, persistence, we can track the sum of the multiplicative persistence and return the result.

Approach 2: Recursion + Helper Function + Ternary Operator

/* 
Recursive helper function that returns the product result of multiplying the digits of a number together
>>> multiplyDigits(43) 
12
*/
function multiplyDigits(num){
  return num < 10 ? num : num % 10 * multiplyDigits(Math.floor(num / 10))
}

/*
Recursive function that returns the count of the multiplicative persistence.
*/
function persistence(num){
  return num < 10 ? 0 : 1 + persistence(multiplyDigits(num))
}

We can retain the same logic as in approach #1 with the addition of using the ternary operator. This is a more succinct way of writing the solution.