Skip to content

Commit 597836e

Browse files
completed and refactored sprint 3 task 2 exercise 3
1 parent 5202e76 commit 597836e

2 files changed

Lines changed: 53 additions & 1 deletion

File tree

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
11
function getOrdinalNumber(num) {
2-
return "1st";
2+
const dictionary = {
3+
1: "st",
4+
2: "nd",
5+
3: "rd",
6+
};
7+
8+
const lastTwoDigit = num % 100;
9+
const lastDigit = num % 10;
10+
11+
if (lastTwoDigit == 11 || lastTwoDigit == 12 || lastTwoDigit == 13) {
12+
return `${num}` + `th`;
13+
}
14+
15+
const ending = dictionary[lastDigit] || "th";
16+
return `${num}${ending}`;
317
}
418

519
module.exports = getOrdinalNumber;

Sprint-3/2-practice-tdd/get-ordinal-number.test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,41 @@ 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, except numbers ending with 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, except numbers ending with 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 should use "th"
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+
42+
expect(getOrdinalNumber(111)).toEqual("111th");
43+
expect(getOrdinalNumber(112)).toEqual("112th");
44+
expect(getOrdinalNumber(113)).toEqual("113th");
45+
});
46+
47+
// Case 5: All other endings should use "th"
48+
test("should append 'th' for numbers that do not end in 1, 2, or 3", () => {
49+
expect(getOrdinalNumber(4)).toEqual("4th");
50+
expect(getOrdinalNumber(5)).toEqual("5th");
51+
expect(getOrdinalNumber(6)).toEqual("6th");
52+
expect(getOrdinalNumber(7)).toEqual("7th");
53+
expect(getOrdinalNumber(8)).toEqual("8th");
54+
expect(getOrdinalNumber(9)).toEqual("9th");
55+
expect(getOrdinalNumber(10)).toEqual("10th");
56+
expect(getOrdinalNumber(20)).toEqual("20th");
57+
expect(getOrdinalNumber(100)).toEqual("100th");
58+
});

0 commit comments

Comments
 (0)