Yah, I know it's sneaky. It's one of the tricks I thought of when I read through the JavaScript and ECMAScript specs recently, and this is the first time I've got to put it to use. Try it: <javascript:alert(Number(Boolean(2)));void(0);>
Oh, just wondering - what might be fastest:
Code:
(( Math.floor((n%100)/10) == 1)
With one scope jump, one property lookup, one function call, one remainder, one division and one comparison, or
Code:
( this % 100 - nModTen != 10 ) * nModeTen
With one remainder, one subtraction, one comparison, one autocasting, and one multiplication.
I believe your code would win out, in those cases. (The access part (scope jump and property lookup) should be fast compared to my math, and the function call and the autocast should both be almost unnoticable) However, my single comparison should make my code faster in the cases of 'th', when I won't have to perform all those numerical operations. So, how would they compare for many numbers, performance wise?
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 n + ["th","st","nd","rd"][(!( ((n%10) >3) || (Math.floor(n%100/10)==1)) ) * (n%10)];
}
This problem is much less complex when handling it as numbers compared to handling it as strings. Math is generally easier to work with than string comparisons, especially when it's a numerical problem.
What about this to test the values in the easiest to follow way:
switch (aNum) {
case 1:
case 21:
case 31:
suffix = 'st';
break;
case 2:
case 22:
suffix = 'nd';
break;
case 3:
case 23:
suffix = 'rd';
break;
default:
suffix = 'th';
}
I think that this is an interesting discussion. I see that there are a number of solutions for this problem. I think, though, that it is always important to generalize when developing script code that could be used in a number of situations. That said, I wrote a short function which will do the trick for any positive or negative integer. The code can be found at http://gotochriswest.com/development...OrdinalFor.php. Alternatively, you can also find it below: