I need help implementing a recursive function. This is my first time attempting recursion outside of the standard 'factorial' that us newbs first learn.
I am able to get the correct answer in the console, but I can't figure out how to make my function recognize that it has produced the correct answer.
The challenge: "Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers."
My attempt:
let num = 19;
let isHappy = (n) => {
let sNum = `${n}`;
let sArray = sNum.split('');
let nArray = sArray.map(el => Number(el))
let total = nArray.reduce((acc, curr) => {
return acc += curr * curr
}, 0);
if(isHappy(total) === 1) {
return true
} else {
return false
}
}
isHappy(num)
I've use while loops and made different attemps at performing the base case test, but no luck. Any help would be greatly appreciated.