Skip to content

Commit f1f96b4

Browse files
committed
Implement getOrdinalNumber
1 parent 1a4ec4e commit f1f96b4

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
11
function getOrdinalNumber(num) {
2-
return "1st";
2+
// handle special cases
3+
4+
if (typeof num !== "number" || Number.isNaN(num)) {
5+
throw new Error(`Invalid type for ${num}, expected Number`);
6+
}
7+
8+
const snum = String(num); // num as a string
9+
const thList = ["0", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]; // list of numbers that should end up with th as a suffix
10+
11+
const lastCharIndex = snum.length - 1;
12+
const lastOne = snum[lastCharIndex];
13+
const lastTwo = snum.slice(lastCharIndex - 1);
14+
15+
if (thList.includes(lastTwo) || thList.includes(lastOne)) {
16+
return snum + "th";
17+
}
18+
19+
switch (lastOne) {
20+
case "1":
21+
return snum + "st";
22+
case "2":
23+
return snum + "nd";
24+
case "3":
25+
return snum + "rd";
26+
default:
27+
break;
28+
}
329
}
430

531
module.exports = getOrdinalNumber;

0 commit comments

Comments
 (0)