Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordinals in words javascript

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"
like image 665
Richard Hutta Avatar asked Apr 14 '13 10:04

Richard Hutta


1 Answers

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.

like image 123
JJJ Avatar answered Sep 23 '22 06:09

JJJ