DEV Community

Discussion on: Solving the Digital Root Algorithm using JavaScript

Collapse
 
darthbob88 profile image
Raymond Price

Cool demo, but that's not actually recursion, that's just iteration. An actual recursive solution, if you wanted to do that for some strange reason, would look more like

function digitalRoot(number) {
   let arr = number.toString().split("");
   let reducer = (a,b) => parseInt(a) + parseInt(b);
   let sum = arr.reduce(reducer)

   if (sum > 9) {
       return digitalRoot(sum);
   } else {
       return sum;
   }
}

Also, sidenote, this function does break on very large numbers. That's not OP's fault, that's because Javascript can't reasonably represent things like 1234567891234567891234567891 as an integer. digitalRoot("1234567891234567891234567891") works just fine, though