This post is more than 2 years old.
The goal of this function wasn't to be a general purpose formatter, rather, it would focus on taking positive integers and writing them in 4 characters or less. So any number below 10000 would be written as is. Any number between 10000 and 1 million would be written as NK. For example: 321K, 981K, 109K. I'd round the numbers down of course. Given 320980 as an input I'd expect 321K as the output. I'd extend similar logic to the millions and billions. After that I wasn't quite sure what I'd do. Here is the function I came up with:
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.