DEV Community

loading...

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

Collapse
savagepixie profile image
SavagePixie

Yes, yes, I know, 2000 should return "21st" century. I don't know of anyone who counts centuries like that, so my function returns them according to normal use.

const addBC = year => year < 0 ? " BC" : ""

const centurify = year => {
   const num = Math.ceil(Math.abs(year) / 100).toString()
   const suffix = num.match(/(11|12|13)$/)
      ? "th" : num.endsWith("1")
      ? "st" : num.endsWith("2")
      ? "nd" : num.endsWith("3")
      ? "rd" : "th"
   return num + suffix + addBC(year)
}
Collapse
citizen428 profile image
Michael Kohl

This may be missing a couple of special cases:

centurify(1124)
'12nd'
> centurify(1213)
'13rd'
Collapse
savagepixie profile image
SavagePixie

It's fixed now (I think). It should also support BC centuries.

Collapse
savagepixie profile image
SavagePixie

Oh, good catch