Skip to content

Commit af1e37a

Browse files
committed
used a simpler % test to get the last digits of a number, added tests for negative and non integer numbers
1 parent d754f5a commit af1e37a

File tree

2 files changed

+38
-23
lines changed

2 files changed

+38
-23
lines changed
Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
function getOrdinalNumber(num) {
2-
const lastDigit = num.toString()[num.toString().length - 1];
2+
if (Number.isInteger(num) && num >= 0) {
3+
const lastDigit = num % 10;
34

4-
if (lastDigit === "1") {
5-
if (num === 11) {
6-
return `${num}th`;
7-
}
8-
9-
return `${num}st`;
10-
} else if (lastDigit === "2") {
11-
if (num.toString().length > 1) {
12-
const last2Digits = num.toString().slice(-2);
13-
14-
if (last2Digits === "12") {
5+
if (lastDigit === 1) {
6+
if (num === 11) {
157
return `${num}th`;
168
}
17-
}
18-
return `${num}nd`;
19-
} else if (lastDigit === "3") {
20-
if (num.toString().length > 1) {
21-
const last2Digits = num.toString().slice(-2);
229

23-
if (last2Digits === "13") {
24-
return `${num}th`;
10+
return `${num}st`;
11+
} else if (lastDigit === 2) {
12+
if (num > 10) {
13+
if (num % 100 === 12) {
14+
return `${num}th`;
15+
}
16+
}
17+
return `${num}nd`;
18+
} else if (lastDigit === 3) {
19+
if (num > 10) {
20+
if (num % 100 === 13) {
21+
return `${num}th`;
22+
}
2523
}
24+
return `${num}rd`;
2625
}
27-
return `${num}rd`;
28-
}
2926

30-
return `${num}th`;
27+
return `${num}th`;
28+
} else {
29+
throw new Error("wrong input used please enter an integer from 0 upwards");
30+
}
3131
}
3232

3333
module.exports = getOrdinalNumber;

Sprint-3/2-practice-tdd/get-ordinal-number.test.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,24 @@ test("should append 'rd' to numbers with 3 at the end except for those ending wi
3333
});
3434

3535
test("should append 'th' to all other numbers which do not end in 1,2,3,11,12 or 13", () => {
36-
expect(getOrdinalNumber(10)).toEqual("10th");
36+
expect(getOrdinalNumber(0)).toEqual("0th");
3737
expect(getOrdinalNumber(11)).toEqual("11th");
3838
expect(getOrdinalNumber(212)).toEqual("212th");
3939
expect(getOrdinalNumber(113)).toEqual("113th");
4040
expect(getOrdinalNumber(17)).toEqual("17th");
4141
});
42+
43+
test("should throw an error if the input anything other than a positive integer", () => {
44+
expect(() => getOrdinalNumber(1.09)).toThrow(
45+
"wrong input used please enter an integer from 0 upwards"
46+
);
47+
expect(() => getOrdinalNumber("thirteen")).toThrow(
48+
"wrong input used please enter an integer from 0 upwards"
49+
);
50+
expect(() => getOrdinalNumber(0.9)).toThrow(
51+
"wrong input used please enter an integer from 0 upwards"
52+
);
53+
expect(() => getOrdinalNumber(-10)).toThrow(
54+
"wrong input used please enter an integer from 0 upwards"
55+
);
56+
});

0 commit comments

Comments
 (0)