Home > database >  Sum of Digits works in console but not when returned
Sum of Digits works in console but not when returned

Time:03-16

So I'm doing a codewars challenge and I have no clue why my code isn't working. I'm a beginner so please don't hate on me.

This is my code:

function digital_root(n) {
    let str = n.toString()
    let arr = []
    let sum = 0
    for (let i = 0; i < str.length; i  ) {
      arr.push(str.charAt(i))
    }
    for (let i = 0; i < str.length; i  ) {
      sum  = Number(arr[i])
    }
    let sumStr = sum.toString()
    if (sumStr.length > 1) {
      digital_root(sum)
    } else  if (sumStr.length == 1) {
        return sum
    }
}

It works when I console.log it but not when I return the value. I'm trying to learn recursion. Thanks for the help!

CodePudding user response:

Ok, it seems you are missing dealing with the return value of digital_root when you call it recursively. See added "return" statement below.

function digital_root(n) {
    let str = n.toString()
    let arr = []
    let sum = 0
    for (let i = 0; i < str.length; i  ) {
      arr.push(str.charAt(i))
    }
    for (let i = 0; i < str.length; i  ) {
      sum  = Number(arr[i])
    }
    let sumStr = sum.toString()
    if (sumStr.length > 1) {
      // ***** You need to deal with the return value of digital_root when you call it. 
      return digital_root(sum)
    } else  if (sumStr.length == 1) {
        return sum
    }
}

CodePudding user response:

You need to return digital_root(sum) too, if sumStr.length > 1 in order to access recursive returned value.

you have to write return digital_root(sum) instead of just digital_root(sum).

check below:

function digital_root(n) {
    let str = n.toString()
    let arr = []
    let sum = 0
    for (let i = 0; i < str.length; i  ) {
      arr.push(str.charAt(i))
    }
    for (let i = 0; i < str.length; i  ) {
      sum  = Number(arr[i])
    }
    let sumStr = sum.toString()
    if (sumStr.length > 1) {
      return digital_root(sum)
    } else  if (sumStr.length == 1) {
        return sum
    }
}

console.log("Digital Root :", digital_root('123456789'));

CodePudding user response:

However, while JavaScript's functional coding style does support recursive functions, we need to be aware that most JavaScript compilers are not currently optimized to support them safely. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.

Please read this,

https://www.sitepoint.com/recursion-functional-javascript/#:~:text=However, while JavaScript's functional coding,parameters from within a loop.

  • Related