Skip to content

Commit 2c8e627

Browse files
wrote function and tests for ordinal numbers
1 parent 3f7a169 commit 2c8e627

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
function getOrdinalNumber(num) {
2-
return "1st";
2+
// Check if input is a number
3+
if (typeof num !== "number" || isNaN(num)) {
4+
throw new Error("Input must be a valid number");
5+
}
6+
7+
const j = num % 10; // checks what last number is
8+
const k = num % 100; // checks what last two numbers are, needed to check for 11
9+
10+
if (k === 11 || k === 12 || k === 13) {
11+
return num + "th";
12+
}
13+
if (j === 1) return num + "st";
14+
if (j === 2) return num + "nd";
15+
if (j === 3) return num + "rd";
16+
17+
return num + "th";
318
}
419

520
module.exports = getOrdinalNumber;

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,40 @@ const getOrdinalNumber = require("./get-ordinal-number");
1313
// Case 1: Numbers ending with 1 (but not 11)
1414
// When the number ends with 1, except those ending with 11,
1515
// Then the function should return a string by appending "st" to the number.
16+
1617
test("should append 'st' for numbers ending with 1, except those ending with 11", () => {
1718
expect(getOrdinalNumber(1)).toEqual("1st");
1819
expect(getOrdinalNumber(21)).toEqual("21st");
1920
expect(getOrdinalNumber(131)).toEqual("131st");
2021
});
22+
23+
// Case 2: Numbers ending with 2
24+
// When the number ends with 2,
25+
// Then the function should return a string by appending "nd" to the number.
26+
27+
test("should append 'nd' for numbers ending with 2", () => {
28+
expect(getOrdinalNumber(2)).toEqual("2nd");
29+
expect(getOrdinalNumber(32)).toEqual("32nd");
30+
expect(getOrdinalNumber(252)).toEqual("252nd");
31+
});
32+
33+
// Case 3: Numbers ending with 3
34+
// When the number ends with 3,
35+
// Then the function should return a string by appending "rd" to the number.
36+
37+
test("should append 'rd' for numbers ending with 3", () => {
38+
expect(getOrdinalNumber(3)).toEqual("3rd");
39+
expect(getOrdinalNumber(33)).toEqual("33rd");
40+
expect(getOrdinalNumber(133)).toEqual("133rd");
41+
});
42+
43+
// Case 4: The remaining numbers
44+
// When the number ends with 1, except those ending with 11
45+
// For all other numbers
46+
// Then the function should return a string by appending "th" to the number.
47+
48+
test("should append 'th' for remaining numbers", () => {
49+
expect(getOrdinalNumber(20)).toEqual("20th");
50+
expect(getOrdinalNumber(11)).toEqual("11th");
51+
expect(getOrdinalNumber(99)).toEqual("99th");
52+
});

0 commit comments

Comments
 (0)