We're a place where coders share, stay up-to-date and grow their careers.
A bit of functional JS
const test = require('./tester'); const century = year => { if (isNaN(year)) return null; const nYear = Number(year); const cent = Math.floor(nYear / 100) + 1; const suffix = Math.floor(cent / 10) % 10 === 1 ? 'th' : cent % 10 === 1 ? 'st' : cent % 10 === 2 ? 'nd' : cent % 10 === 3 ? 'rd' : 'th'; return `${cent}${suffix}`; } test(century, [ { in: [2259], out: '23rd', }, { in: [1124], out: '12th', }, { in: [2000], out: '21st' }, { in: [11092], out: '111th', }, ]);
I like your approach, it looks very clean.
This is probably too fringe to matter in most contexts, but wouldn't your function return 111st for the year 11,092?
It would, indeed. Thanks for pointing out. Now I have fixed it and added a new test case.
OLD SOLUTION (Line 7)
const suffix = Math.floor(cent / 10) === 1 ? 'th'
UPDATED SOLUTION (Line 7)
const suffix = Math.floor(cent / 10) % 10 === 1 ? 'th'
A bit of functional JS
I like your approach, it looks very clean.
This is probably too fringe to matter in most contexts, but wouldn't your function return 111st for the year 11,092?
It would, indeed. Thanks for pointing out. Now I have fixed it and added a new test case.
OLD SOLUTION (Line 7)
UPDATED SOLUTION (Line 7)