toOrdinal()
JavaScript performance comparison
Preparation code
<div id="result"></di>
<script>
Benchmark.prototype.setup = function() {
Number.prototype.toOrdinal1 = function () {
var last = this.toString().substr( -1 );
if( ['11','12','13'].indexOf( this.toString().substr( -2 ) ) > -1 ) {
return this + 'th';
} else if( last == '1' ) {
return this + 'st';
} else if( last == '2' ) {
return this + 'nd';
} else if( last == '3' ) {
return this + 'rd';
} else {
return this + 'th';
};
};
Number.prototype.toOrdinal2 = function () {
if( [11,12,13].indexOf( this % 100 ) > -1 ) {
return this + 'th';
} else {
return this + ['th','st','nd','rd','th','th','th','th','th','th'][this % 10];
};
};
Number.prototype.toOrdinal3 = function()
{
var n = this % 100;
var suff = ["th", "st", "nd", "rd", "th"]; // suff for suffix
var ord= n<21?(n<4 ? suff[n]:suff[0]): (n%10>4 ? suff[0] : suff[n%10]);
return this + ord;
}
var result = document.getElementById( 'result' );
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
toOrdinal1() |
|
pending… |
toOrdinal2() |
|
pending… |
toOrdinal3() |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments