What Century

"What century is it?" code kata from the CodeWars website.

Description:
Return the inputted numerical year in century format. For example 2014, would return 21st.
The input will always be a 4 digit string. So there is no need for year string validation

Examples:
Input: 1999 Output: 20th
Input: 2011 Output: 21st
Input: 2154 Output: 22nd
Input: 2259 Output: 23rd
Input: 1124 Output: 12th
Input: 2000 Output: 20th

Code notes:
- After doing the basic century math, I couldn't recall how to cast a decimal to a number offhand, so I just cast it as a string instead.
Language:
JavaScript
Keywords:
Code Snippet

function whatCentury(year) {
var c = ( (parseInt(year) + 99) / 100 ).toString();
var outval = c[0] + c[1];
outval += ( c[
0] == 1 && c[1] == 1 ) ? "th"
: ( c[0] == 1 && c[1] == 2 ) ? "th"
: ( c[0] == 1 && c[1] == 3 ) ? "th"
: ( c[1] == 0 ) ? "th"
: ( c[1] == 1 ) ? "st"
: ( c[1] == 2 ) ? "nd"
: ( c[1] == 3 ) ? "rd"
: "th"
return outval;
}

Example

Unit Tests:

Test.assertEquals(whatCentury("1999"), "20th", "With input '1999' solution produced wrong output");
Test.assertEquals(whatCentury(
"2011"), "21st", "With input '2011' solution produced wrong output");
Test.assertEquals(whatCentury(
"2154"), "22nd", "With input '2154' solution produced wrong output");
Test.assertEquals(whatCentury(
"2259"), "23rd", "With input '2259' solution produced wrong output");
Test.assertEquals(whatCentury(
"1234"), "13th", "With input '1234' solution produced wrong output");
Test.assertEquals(whatCentury(
"1023"), "11th", "With input '1023' solution produced wrong output");
Test.assertEquals(whatCentury(
"2000"), "20th", "With input '2000' solution produced wrong output");


Created 2014-03-29
comments powered by Disqus
Login