Algorithms 101: Happy Number in JavaScript

Noob v. Algorithms #14, using .reduce(), recursion and default parameters

Joan Indiana Lyness
Oct 18 · 4 min read
from wikimedia commons

If you’ve ever found happiness elusive, you’ll be happy to know that there is such a thing as a happy number. LeetCode describes it like so:

var isHappy = function(n){//write code here}

Here’s the link to the challenge on LeetCode.

So, how do we write code that returns true if a number ’n’ is happy?

Using the example above, we would follow these steps:

  1. break the number 19 into separate digits of 1 and 9.

Steps 1 & 2: Break the number into digits and square each digit

Let’s say n is 19. Here’s how the code above works, step by step:

Step 3: Sum the squares, using .reduce()

In JavaScript, anytime you want to reduce an array to a single value, you can use the reduce function, which takes a function as an argument.

writing this out longhand to make it easier to understand!

In the code above, array.reduce() takes a callback function. This callback sets the sum to an initial value of zero. Then it loops over every item in the array,

In the first loop, it adds currentItem to the initial value, 0. It stores the sum in accumulator. In subsequent loops, it adds currentItem to accumulator. When it’s done, sum equals the sum of all the elements in the array.

Pictures help! For an excellent gif on how this works, look here.

Once you understand the concept, you can shorten your .reduce() code to this:

shorthand

Steps 4 & 5: Check the sum: return true if it equals one.

Step 6, the hard part: How exactly do you start over?

I wanted to code a recursive solution, like this.

But if sum never equals one, the function will continue in an infinite loop. Noooooo !

obligatory infinite loop giphy

To stop this from happening, we need a base case. In other words, when do we want this function to stop calling itself?

If a number is happy, sum eventually resolves to 1. But if it is not happy, I’m not sure what happens (I don’t know that much about number theory). So I decided the function should call itself a finite amount of times.

To make this happen, I wanted to add a counter.

That’s hard to do in a recursive function. I’m used to setting an initial value for a counter near the top of the function, i.e.: let counter = 0. But if you do that in a recursive function, your counter is reset to zero with each recursion.

To get around this, you can pass the counter into your function as an argument with a default value of zero.

If counter is passed in with a value, the function will use that value; but if counter is passed in with no value, the function will read counter as 0. (Here’s MDN documentation on default parameters.)

Let’s unpack that.

We are going to return ‘result’ at the end of our function. We give result an initial value of false.

Then, starting on line 5, as long as we have tried fewer than 8 times, we break n into its digits, square them, sum the squares, and check to see if the sum is 1. If it is, we set result equal to true and break out of the loop. Otherwise, we increment our counter and start over.

Note: first I tried 5 as the maximum number of loops; it didn’t pass LeetCode tests, so I upped the number to 8, which did work.

And, it worked well!

You can play with the code here on repl.it: https://repl.it/@Joan_IndianaInd/Happy-Number

Copyright © Joan Indiana Lyness 2019

Next: Algorithms 101 #15, Can Place Flowers in JavaScript

In case you missed it: Algorithms 101, #13: Pascal’s Triangle in JavaScript

JavaScript in Plain English

Learn the web's most important programming language.

Joan Indiana Lyness

Written by

Hire me in Washington DC! Full-stack developer, Ruby, Rails, JavaScript, i love! React. My portfolio: https://joan-indiana-lyness.com/projects

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade