View Single Post
Old 03-26-2010, 04:02 PM   PM User | #32
bardonw
New Coder

 
Join Date: Dec 2009
Posts: 11
Thanks: 1
Thanked 0 Times in 0 Posts
bardonw is an unknown quantity at this point
Quote:
Originally Posted by RoyW View Post
I like the boolean trick and I like the idea of only having 4 strings in the array
Code:
function num_abbrev_str(n)
{
    return n + ["th","st","nd","rd"][!(n%10>3||Math.floor(n%100/10)==1)*n%10]; 
}
In this 60% of the time the
(n%10>3)
will be true so the
Math.floor(n%100/10)==1
will only be executed for 40% of the numbers.

Invert the boolean and do the multiply
NOTE: I have utilised operator precedence to reduce char count.
Here is a version with parentheses to show precedence
PHP Code:
function num_abbrev_str(n)
{
    return 
+ ["th","st","nd","rd"][(!( ((n%10) >3) || (Math.floor(n%100/10)==1)) ) * (n%10)]; 

I must admit, this is some impressive code! After seeing this I decided to optimize it just a bit by storing the array of suffixes privately. After doing that and modifying it to have the same footprint as my generic function, I ended up with the following code:
Code:
var num_abbrev_str = (function()
{
	var z = ["th","st","nd","rd"];
	return function(intNum, includeNumber)
	{
		return (includeNumber ? intNum : "") + z[!((intNum = Math.abs(intNum))
			% 10 > 3 || Math.floor(intNum % 100 / 10) == 1) * intNum % 10];
	};
})();
The plus side is, the function works very well. The only disadvantage is, on Internet Explorer and Firefox, this function takes longer to run, for a large number of integers, than the code below does. On the other hand, I doubt that too many people will be running this type of function for 100,000+ numbers.
Code:
function num_abbrev_str(intNum, includeNumber)
{
	return (includeNumber ? intNum : "") + (((intNum = Math.abs(intNum) % 100)
		% 10 == 1 && intNum != 11) ? "st" : (intNum % 10 == 2 && intNum != 12)
		? "nd" : (intNum % 10 == 3 && intNum != 13) ? "rd" : "th");
}
Still, your code is most impressive.

Last edited by bardonw; 03-26-2010 at 04:09 PM..
bardonw is offline   Reply With Quote