Skip to content

Commit 714b6fa

Browse files
committed
Write tests and implement the function for Get Ordinal Number task
1 parent 0f801bb commit 714b6fa

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

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

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,25 @@
11
export function getOrdinalNumber(num) {
2-
return "1st";
2+
if (num === null || num === undefined || num === "" || num < 0) {
3+
throw new Error("Invalid input!");
4+
}
5+
6+
if (typeof num !== "number" || !isFinite(num)) {
7+
throw new Error("Invalid input!");
8+
}
9+
10+
const lastDigit = num % 10;
11+
const lastTwoDigits = num % 100;
12+
13+
if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
14+
return `${num}th`;
15+
}
16+
17+
if (lastDigit === 1) {
18+
return `${num}st`;
19+
} else if (lastDigit === 2) {
20+
return `${num}nd`;
21+
} else if (lastDigit === 3) {
22+
return `${num}rd`;
23+
}
24+
return `${num}th`;
325
}

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,29 @@ 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+
test("should append 'nd' for numbers ending with 2, except those ending with 12", () => {
23+
expect(getOrdinalNumber(2)).toEqual("2nd");
24+
expect(getOrdinalNumber(32)).toEqual("32nd");
25+
expect(getOrdinalNumber(102)).toEqual("102nd");
26+
});
27+
28+
test("should append 'rd' for numbers ending with 3, except those ending with 13", () => {
29+
expect(getOrdinalNumber(3)).toEqual("3rd");
30+
expect(getOrdinalNumber(53)).toEqual("53rd");
31+
expect(getOrdinalNumber(123)).toEqual("123rd");
32+
});
33+
34+
test("should append 'th' for the rest of the numbers", () => {
35+
expect(getOrdinalNumber(9)).toEqual("9th");
36+
expect(getOrdinalNumber(20)).toEqual("20th");
37+
expect(getOrdinalNumber(108)).toEqual("108th");
38+
});
39+
40+
test("should throw an error if the input is invalid", () => {
41+
expect(() => getOrdinalNumber("")).toThrow("Invalid input!");
42+
expect(() => getOrdinalNumber("fifty two")).toThrow("Invalid input!");
43+
expect(() => getOrdinalNumber(-3)).toThrow("Invalid input!");
44+
expect(() => getOrdinalNumber(null)).toThrow("Invalid input!");
45+
expect(() => getOrdinalNumber(undefined)).toThrow("Invalid input!");
46+
});

0 commit comments

Comments
 (0)