DEV Community

loading...

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

Collapse
gnsp profile image
Ganesh Prasad

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',
    },
]);
Collapse
savagepixie profile image
SavagePixie

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?

Collapse
gnsp profile image
Ganesh Prasad

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'