Your solution makes sense, mathematically.
However, I think it's a wasted chance to use and explain recursion with carryover.
The function can be something like this:
function isHappy(n, seenSums = []) {
// ... same as above
if (sum === 1) return true; // answer found
if (seenSums.includes(sum)) return false; // generic infinite loop detection mechanism
return isHappy(sum, seenSums.concat([sum])); // recursion with carryover
}
Your solution makes sense, mathematically.
However, I think it's a wasted chance to use and explain recursion with carryover.
The function can be something like this:
You could use
Set
instead of an array forseenSums
, that way your validation to check the infinite loop could be done in constant time by changingfor