Skip to content

Commit fb90283

Browse files
committed
Add input validation to ensure the function only accept valid card values and update the test case.
1 parent d34b464 commit fb90283

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed
Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,39 @@
11
function getCardValue(card) {
2-
const rank = card.slice(0, -1); // get the value part: A, 2–10, J, Q, K
2+
if (typeof card !== "string") {
3+
throw new Error("Card must be a string");
4+
}
5+
6+
card = card.trim().toUpperCase();
7+
8+
// Extract rank (everything except last char, assuming last is suit)
9+
const rank = card.slice(0, -1);
10+
11+
// Define allowed ranks exactly — no fuzzy matching
12+
const validRanks = [
13+
"2",
14+
"3",
15+
"4",
16+
"5",
17+
"6",
18+
"7",
19+
"8",
20+
"9",
21+
"10",
22+
"J",
23+
"Q",
24+
"K",
25+
"A",
26+
];
27+
28+
if (!validRanks.includes(rank)) {
29+
throw new Error("Invalid card rank");
30+
}
331

432
if (rank === "A") return 11;
533
if (["K", "Q", "J"].includes(rank)) return 10;
634

7-
const number = parseInt(rank);
8-
if (!isNaN(number) && number >= 2 && number <= 10) return number;
9-
10-
throw new Error("Invalid card");
35+
// If rank is numeric (2-10), safely convert to number
36+
return parseInt(rank, 10);
1137
}
1238

1339
module.exports = getCardValue;

Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,26 @@ test("throws an error or invalid card", () => {
2020
expect(() => getCardValue("Z♠")).toThrow("Invalid card");
2121
});
2222

23+
test("should throw error for malformed numeric input", () => {
24+
expect(() => getCardValue("2.9999♠")).toThrow("Invalid card rank");
25+
});
26+
27+
test("should throw error for repeated characters in rank", () => {
28+
expect(() => getCardValue("3AAAA♠")).toThrow("Invalid card rank");
29+
});
30+
31+
test("should throw error for number beyond valid range", () => {
32+
expect(() => getCardValue("11♠")).toThrow("Invalid card rank");
33+
});
34+
35+
test("should throw error for missing suit", () => {
36+
expect(() => getCardValue("Q")).toThrow("Invalid card rank");
37+
});
38+
39+
test("should throw error for non-string input", () => {
40+
expect(() => getCardValue(5)).toThrow("Card must be a string");
41+
});
42+
2343
// try {
2444
// getCardValue("Z♠");
2545
//} catch (error) {

0 commit comments

Comments
 (0)