Skip to content

Commit bdcd308

Browse files
Add tests and implementation for get-ordinal-number
1 parent 021283e commit bdcd308

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

‎practice-tdd/get-ordinal-number.js‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
11
export function getOrdinalNumber(num) {
2-
return "1st";
3-
}
2+
const lastTwoDigits = num % 100;
3+
if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
4+
return `${num}th`;
5+
}
6+
7+
const lastDigit = num % 10;
8+
if (lastDigit === 1) return `${num}st`;
9+
if (lastDigit === 2) return `${num}nd`;
10+
if (lastDigit === 3) return `${num}rd`;
11+
return `${num}th`;
12+
}

‎practice-tdd/get-ordinal-number.test.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,33 @@ test("should append 'st' for numbers ending with 1, except those ending with 11"
1818
expect(getOrdinalNumber(21)).toEqual("21st");
1919
expect(getOrdinalNumber(131)).toEqual("131st");
2020
});
21+
22+
// Case 2: Numbers ending with 2 (but not 12)
23+
test("should append 'nd' for numbers ending with 2, except those ending with 12", () => {
24+
expect(getOrdinalNumber(2)).toEqual("2nd");
25+
expect(getOrdinalNumber(22)).toEqual("22nd");
26+
expect(getOrdinalNumber(132)).toEqual("132nd");
27+
});
28+
29+
// Case 3: Numbers ending with 3 (but not 13)
30+
test("should append 'rd' for numbers ending with 3, except those ending with 13", () => {
31+
expect(getOrdinalNumber(3)).toEqual("3rd");
32+
expect(getOrdinalNumber(23)).toEqual("23rd");
33+
expect(getOrdinalNumber(133)).toEqual("133rd");
34+
});
35+
36+
// Case 4: Numbers ending with 11, 12 or 13
37+
test("should append 'th' for numbers ending with 11, 12 or 13", () => {
38+
expect(getOrdinalNumber(11)).toEqual("11th");
39+
expect(getOrdinalNumber(12)).toEqual("12th");
40+
expect(getOrdinalNumber(13)).toEqual("13th");
41+
expect(getOrdinalNumber(111)).toEqual("111th");
42+
});
43+
44+
// Case 5: All other numbers
45+
test("should append 'th' for all other numbers", () => {
46+
expect(getOrdinalNumber(4)).toEqual("4th");
47+
expect(getOrdinalNumber(10)).toEqual("10th");
48+
expect(getOrdinalNumber(25)).toEqual("25th");
49+
expect(getOrdinalNumber(100)).toEqual("100th");
50+
});

0 commit comments

Comments
 (0)