Skip to content

Commit 2db8252

Browse files
authored
editing the code
1 parent 099a76f commit 2db8252

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed
Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,34 @@
11
function getOrdinalNumber(num) {
2-
num = num.toString();
3-
const lastTwo = num.slice(-2);
4-
const lastOne = num.slice(-1);
2+
if (typeof num !== "number" || isNaN(num)) {
3+
return "Invalid input";
4+
}
5+
const sign = num < 0 ? "-" : "";
6+
num = Math.abs(num);
57

6-
if (['11', '12', '13'].includes(lastTwo)) {
7-
return num + 'th';
8+
// Handle decimals
9+
if (!Number.isInteger(num)) {
10+
return sign + num + "th";
811
}
912

13+
const lastTwo = num % 100;
14+
const lastOne = num % 10;
15+
16+
// Handle special cases 11th, 12th, 13th
17+
if (lastTwo >= 11 && lastTwo <= 13) {
18+
return sign + num + "th";
19+
}
20+
21+
// Normal ordinal rules
1022
switch (lastOne) {
11-
case '1': return num + 'st';
12-
case '2': return num + 'nd';
13-
case '3': return num + 'rd';
14-
default: return num + 'th';
23+
case 1:
24+
return sign + num + "st";
25+
case 2:
26+
return sign + num + "nd";
27+
case 3:
28+
return sign + num + "rd";
29+
default:
30+
return sign + num + "th";
1531
}
1632
}
1733

18-
module.exports = getOrdinalNumber;
19-
34+
module.exports = getOrdinalNumber;

0 commit comments

Comments
 (0)