DEV Community

Discussion on: Daily Challenge #54 - What century is it?

Collapse
 
chrisachard profile image
Chris Achard

Ah, this one was tricker than I thought because of the edge cases.

I choose a solution in JS that lists out all the endings in an object - but since they are almost all the same, maybe I should have done something else :)

Also, since I've started recording me solving these, you can check it out here: youtube.com/watch?v=ozws2mzhqkM

const centuryName = year => {
  const endings = {
    0: 'th',
    1: 'st',
    2: 'nd',
    3: 'rd',
    4: 'th',
    5: 'th',
    6: 'th',
    7: 'th',
    8: 'th',
    9: 'th',
  }

  const century = Math.floor(year / 100) + 1
  const rem = century % 10
  const ending = [11, 12, 13].includes(century % 100) 
    ? 'th' : endings[rem]
  return `${century}${ending}`
}