Skip to content

Commit 94e6563

Browse files
committed
get-ordinal-number.js committed
1 parent 26fe90c commit 94e6563

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,36 @@
1+
/**
12
function getOrdinalNumber(num) {
23
return "1st";
34
}
45
56
module.exports = getOrdinalNumber;
7+
*
8+
*/
9+
10+
function getOrdinalNumber(num) {
11+
// Handle negative numbers by preserving the sign
12+
const absoluteNum = Math.abs(num);
13+
const sign = num < 0 ? "-" : "";
14+
15+
// Special cases for 11, 12, 13
16+
const lastTwoDigits = absoluteNum % 100;
17+
if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
18+
return `${sign}${absoluteNum}th`;
19+
}
20+
21+
// Check the last digit for other cases
22+
const lastDigit = absoluteNum % 10;
23+
switch (lastDigit) {
24+
case 1:
25+
return `${sign}${absoluteNum}st`;
26+
case 2:
27+
return `${sign}${absoluteNum}nd`;
28+
case 3:
29+
return `${sign}${absoluteNum}rd`;
30+
default:
31+
return `${sign}${absoluteNum}th`;
32+
}
33+
}
34+
35+
module.exports = getOrdinalNumber;
36+

0 commit comments

Comments
 (0)