Skip to content

Commit a78d633

Browse files
committed
feat: add what century is it solution
1 parent f8c760f commit a78d633

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

codewars/what-century-is-it/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# What Century Is It?
2+
3+
## Description
4+
5+
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.
6+
7+
Examples
8+
9+
```txt
10+
"1999" --> "20th"
11+
"2011" --> "21st"
12+
"2154" --> "22nd"
13+
"2259" --> "23rd"
14+
"1124" --> "12th"
15+
"2000" --> "20th"
16+
```
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const whatCentury = (year) => {
2+
const suffixRules = [
3+
{ suffix: 'st', rule: (c) => c % 10 === 1 && c % 100 !== 11 },
4+
{ suffix: 'nd', rule: (c) => c % 10 === 2 && c % 100 !== 12 },
5+
{ suffix: 'rd', rule: (c) => c % 10 === 3 && c % 100 !== 13 },
6+
{ suffix: 'th', rule: () => true },
7+
];
8+
const century = Math.ceil(year / 100);
9+
const { suffix } = suffixRules.find((rule) => rule.rule(century));
10+
return `${century}${suffix}`;
11+
};
12+
13+
module.exports = whatCentury;
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
const whatCentury = require('./solution');
2+
3+
describe('What Century Is It', () => {
4+
const testCases = [
5+
{
6+
input: 2023,
7+
output: '21st',
8+
},
9+
{
10+
input: 2000,
11+
output: '20th',
12+
},
13+
{
14+
input: 1901,
15+
output: '20th',
16+
},
17+
{
18+
input: 1899,
19+
output: '19th',
20+
},
21+
{
22+
input: '1999',
23+
output: '20th',
24+
},
25+
{
26+
input: '2011',
27+
output: '21st',
28+
},
29+
{
30+
input: '2154',
31+
output: '22nd',
32+
},
33+
{
34+
input: '2259',
35+
output: '23rd',
36+
},
37+
{
38+
input: '1234',
39+
output: '13th',
40+
},
41+
{
42+
input: '1023',
43+
output: '11th',
44+
},
45+
{
46+
input: '2000',
47+
output: '20th',
48+
},
49+
];
50+
51+
it('should return a string type', () => {
52+
expect(typeof whatCentury(2023)).toBe('string');
53+
});
54+
55+
it.each(testCases)('should return $output', (testCase) => {
56+
expect(whatCentury(testCase.input)).toBe(testCase.output);
57+
});
58+
});

0 commit comments

Comments
 (0)