Is there any elegant way how to get ordinals in word format in js/coffee? Something like this:
ordinalInWord(1) # => "first"
ordinalInWord(2) # => "second"
ordinalInWord(5) # => "fifth"
I'm afraid the ordinals aren't regular enough to avoid typing each of them out.
function ordinalInWord( cardinal ) {
var ordinals = [ 'zeroth', 'first', 'second', 'third' /* and so on */ ];
return ordinals[ cardinal ];
}
If you need the function work past 20, you can take advantage of the pattern that emerges:
function ordinalInWord( cardinal ) {
var ordinals = [ 'zeroth', 'first', 'second', 'third' /* and so on up to "twentieth" */ ];
var tens = {
20: 'twenty',
30: 'thirty',
40: 'forty' /* and so on up to 90 */
};
var ordinalTens = {
30: 'thirtieth',
40: 'fortieth',
50: 'fiftieth' /* and so on */
};
if( cardinal <= 20 ) {
return ordinals[ cardinal ];
}
if( cardinal % 10 === 0 ) {
return ordinalTens[ cardinal ];
}
return tens[ cardinal - ( cardinal % 10 ) ] + ordinals[ cardinal % 10 ];
}
Demo: http://jsfiddle.net/AQCqK/
Expanding that to work past 99 shouldn't be difficult.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With