Chris Jones - 3 months ago 5x

Javascript Question

Here I have a function that should take a number

`n`

`disHappy(n)`

`n in [n-0`

Happy Numbers wikipedia

If I only run

`happyChecker(n)`

`disHappy(n)`

`console.log()'s`

`console.log()`

`return true;`

`if(newNum===1)`

`function happyChecker(n) {`

var arr = [];

var newNum = 0;

//here I split a number into a string then into an array of strings//

num = n.toString().split("");

for (var i = 0; i < num.length; i++) {

arr[i] = parseInt(num[i], 10);

}

//here I square each number then add it to newNum//

for (var i = 0; i < arr.length; i++) {

newNum += Math.pow(arr[i], 2);

}

//here I noticed that all unhappy numbers eventually came into one of these three//

//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//

if (newNum === 58 || newNum === 4 || newNum == 37) {

return false;

}

if (newNum === 1) {

return true;

} else {

happyChecker(newNum);

}

}

function disHappy(num) {

for (j = num; j > 0; j--) {

if (happyChecker(j)) {

console.log(j + " is a Happy Number. It's so happy!!!.");

}

}

}

Answer

When you recurse, you need to `return`

the value returned:

```
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
```

You also should declare "num" with `var`

.

I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the `.reduce()`

function to traverse the array of digit characters and do the work of squaring and summing all at once:

```
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
```

The call to `.toString()`

returns a string, then `.split('')`

gives you an array. Then `.reduce()`

starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of `parseInt()`

I just used the `+`

unary operator; we know for sure that each string will be a valid number and an integer.)

Source (Stackoverflow)

Comments