Reduce sum of digits recursively down to a one-digit number JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function that takes in a number and keeps adding its digit until the result is not a one-digit number, when we have a one-digit number, we return it.

The code for this is pretty straightforward, we write a recursive function that keeps adding digit until the number is greater than 9 or lesser than -9 (we will take care of sign separately so that we don’t have to write the logic twice)

Example

const sumRecursively = (n, isNegative = n < 0) => {
   n = Math.abs(n);
   if(n > 9){
      return sumRecursively(parseInt(String(n).split("").reduce((acc,val) => {
         return acc + +val;
      }, 0)), isNegative);
   }
   return !isNegative ? n : n*-1;
};
console.log(sumRecursively(88));
console.log(sumRecursively(18));
console.log(sumRecursively(-345));
console.log(sumRecursively(6565));

Output

The output in the console will be −

7
9
-3
4
raja
Published on 24-Aug-2020 06:04:18
Advertisements