Skip to content

Commit 4a9765b

Browse files
Implement the function and test.
1 parent 19ad0d2 commit 4a9765b

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed
Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,26 @@
1+
12
function getOrdinalNumber(num) {
2-
return "1st";
3+
const absNum = Math.abs(num); // handle negative numbers
4+
const lastTwo = absNum % 100; // get last two digits
5+
const lastDigit = absNum % 10; // get last digit
6+
7+
if (lastTwo >= 11 && lastTwo <= 13) {
8+
return num + "th"; // exceptions: 11,12,13
9+
}
10+
11+
switch (lastDigit) {
12+
case 1:
13+
return num + "st";
14+
case 2:
15+
return num + "nd";
16+
case 3:
17+
return num + "rd";
18+
default:
19+
return num + "th";
20+
}
321
}
22+
console.log(getOrdinalNumber(12)); //printed 12th.
23+
console.log(getOrdinalNumber(123)); // printed 123rd.
24+
console.log(getOrdinalNumber(52)); // printed 52nd.
425

526
module.exports = getOrdinalNumber;

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,31 @@ 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+
// When the number ends with 2, except those ending with 12,
24+
// Then the function should return a string by appending "nd" to the number.
25+
test("should append 'nd' for numbers ending with 2, except those ending with 12", () => {
26+
expect(getOrdinalNumber(2)).toEqual("2nd");
27+
expect(getOrdinalNumber(22)).toEqual("22nd");
28+
expect(getOrdinalNumber(132)).toEqual("132nd");
29+
});
30+
31+
// Case 3:Numbers ending with 3 (but not 13)
32+
//When the number ends with 3, except those ending with 13,
33+
//Then the function should return a string by appending "rd" to the number.
34+
test("should append 'rd' for numbers ending with 3, except those ending with 13", () => {
35+
expect(getOrdinalNumber(3)).toEqual("3rd");
36+
expect(getOrdinalNumber(23)).toEqual("23rd");
37+
expect(getOrdinalNumber(133)).toEqual("133rd");
38+
});
39+
40+
// Case 4: Numbers ending with (0, 4-9,11-13)
41+
// //Then the function should return a string by appending "th" to the number.
42+
test("should append 'th' for numbers ending with 0, 4-9, or 11-13", () => {
43+
expect(getOrdinalNumber(4)).toEqual("4th");
44+
expect(getOrdinalNumber(10)).toEqual("10th");
45+
expect(getOrdinalNumber(11)).toEqual("11th");
46+
expect(getOrdinalNumber(12)).toEqual("12th");
47+
expect(getOrdinalNumber(13)).toEqual("13th");
48+
});

0 commit comments

Comments
 (0)