Skip to content

Commit 5ad4155

Browse files
refactor: simplify getOrdinalNumber function for clarity and efficiency
1 parent 7c2f507 commit 5ad4155

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed
Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,15 @@
11
function getOrdinalNumber(num) {
2-
const absNum = Math.abs(num);
3-
const lastTwoDigits = absNum % 100;
4-
5-
if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
6-
return `${num}th`;
7-
}
8-
9-
const lastDigit = absNum % 10;
10-
11-
if (lastDigit === 1) {
12-
return `${num}st`;
13-
}
14-
15-
if (lastDigit === 2) {
16-
return `${num}nd`;
17-
}
18-
19-
if (lastDigit === 3) {
20-
return `${num}rd`;
21-
}
22-
23-
return `${num}th`;
2+
let numberToString = String(num);
3+
let numberLastDigit = numberToString.slice(-1);
4+
let numberLast2Digits = numberToString.slice(-2);
5+
6+
if (numberLastDigit === "1" && numberLast2Digits !== "11")
7+
return numberToString + "st";
8+
if (numberLastDigit === "2" && numberLast2Digits !== "12")
9+
return numberToString + "nd";
10+
if (numberLastDigit === "3" && numberLast2Digits !== "13")
11+
return numberToString + "rd";
12+
return numberToString + "th";
2413
}
2514

2615
module.exports = getOrdinalNumber;

0 commit comments

Comments
 (0)