0

I want to create a function that receives a number, the number will be reduced to the sum of its digits (16 is reduced to 7 -> return 7) until the result is just one digit long (326 is reduced to 11 and then reduced to 2 -> return 2).

I am creating a recursive function as follows, but it returns undefined for digits whose length is > 1.

function digital_root(n) {
   var numStr = (typeof n == "string") ? n : n.toString(); // ensure we will use a string
   //console.log("evaluating " + numStr + "its length is " + numStr.length);
   //now evaluate my base case
   if (numStr.length <= 1){
     console.log("i will return" + numStr)//should return my 1 digit number
     return n; //it doesn't
   }
   else{
     var arr = numStr.split(""); //convert the string into an array
     var reducedArr = arr.reduce(function(a,b){
       return parseInt(a) + parseInt(b);//sum the elements of the array
     });
     digital_root(reducedArr);//send the reduced value back for evaluation
  }
}
digital_root(16)//returns undefined

I've seen a few similar questions but they address only the code and not the concept. the way i've learned recursion is that you have a base case that you evaluate, if it's true then return -this will be end of the recursion-, if not, go ahead and run the code that will transform the data that will be sent again for evaluation.

how can I avoid the undefined result and is my conception of recursion accurate?

1
  • 4
    return digital_root(reducedArr) Commented Sep 14, 2016 at 0:47

1 Answer 1

4
return digital_root(reducedArr);

You are missing a return in the else branch. A function that does not execute return will yield undefined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.