Skip to content

Commit 4153632

Browse files
committed
Refactor getOrdinalNumber function to return early for invalid input and remove redundant code
1 parent 2b82934 commit 4153632

File tree

1 file changed

+21
-27
lines changed

1 file changed

+21
-27
lines changed
Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,25 @@
11
function getOrdinalNumber(num) {
2-
let ordinalNum;
3-
if (Number.isInteger(num) === true) {
4-
if (
5-
Math.abs(num % 100) === 11 ||
6-
Math.abs(num % 100) === 12 ||
7-
Math.abs(num % 100) === 13 ||
8-
Math.abs(num % 10) === 4 ||
9-
Math.abs(num % 10) === 5 ||
10-
Math.abs(num % 10) === 6 ||
11-
Math.abs(num % 10) === 7 ||
12-
Math.abs(num % 10) === 8 ||
13-
Math.abs(num % 10) === 9 ||
14-
Math.abs(num % 10) === 0
15-
) {
16-
ordinalNum = `${num}th`;
17-
} else if (Math.abs(num % 10) === 1) {
18-
ordinalNum = `${num}st`;
19-
} else if (Math.abs(num % 10) === 2) {
20-
ordinalNum = `${num}nd`;
21-
} else if (Math.abs(num % 10) === 3) {
22-
ordinalNum = `${num}rd`;
23-
} else {
24-
ordinalNum = `${num}th`;
25-
}
26-
} else {
27-
ordinalNum = "Invalid input: Input is an integer";
2+
// Early return for invalid inputs
3+
if (!Number.isInteger(num)) {
4+
return "Invalid input: Input is an integer";
285
}
29-
return ordinalNum;
6+
7+
const absNum = Math.abs(num);
8+
const lastTwo = absNum % 100;
9+
const lastDigit = absNum % 10;
10+
11+
// Handle special cases: 11th, 12th, 13th
12+
if (lastTwo === 11 || lastTwo === 12 || lastTwo === 13) {
13+
return `${num}th`;
14+
}
15+
16+
// Handle regular suffixes
17+
if (lastDigit === 1) return `${num}st`;
18+
if (lastDigit === 2) return `${num}nd`;
19+
if (lastDigit === 3) return `${num}rd`;
20+
21+
// Default suffix
22+
return `${num}th`;
3023
}
24+
3125
module.exports = getOrdinalNumber;

0 commit comments

Comments
 (0)