Not really rocket science, and I’m sure it could be done better, but you get the idea. The only thing really weird here, and something I may change my mind on, is that I took values in the “single” millions (i.e. 5190981) and returned it with decimal places: 5.20M. In my mind, the data I would use this function in would have more distribution in this area so I thought it might make sense to get a bit more precise there. Obviously this is very much a personal preference and could be easily changed.
While working on my code, I used some simple console logging to test my function:
Here is the test spec I wrote for my code. If this is the very first time you’ve seen Jasmine, I can pretty much guarantee that you will be able to figure out what this does.
As just a quick reminder - this is my first Jasmine unit test. I’m not calling this a good test. But it worked.
Once I had this, I simply opened up the file in my browser. As I worked on my tests, and my function, I just hit reload to ensure my tests kept passing.
If you want, you can run this yourself here: http://www.raymondcamden.com/demos/2012/jul/6/jasminetest/SpecRunner.html
While my unit test was quite a bit longer than my simple console test, I really felt like it was a much better way to ensure my function worked correctly. I had nicely separated blocks of tests that hit each part of my code’s functionality. (Although I’m sure more could be added.) If anything did go wrong, I’d have a better idea of where the issue was as opposed to my simple long list of numbers.