Skip to content

Commit faa279a

Browse files
committed
refactor: change let variables to const and add early validation for suit and rank
1 parent 8adf134 commit faa279a

File tree

1 file changed

+39
-30
lines changed

1 file changed

+39
-30
lines changed

Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js

Lines changed: 39 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,42 +23,51 @@
2323

2424
function getCardValue(card) {
2525
const validSuits = ["♠", "♥", "♦", "♣"];
26+
const validRanks = [
27+
"A",
28+
"1",
29+
"2",
30+
"3",
31+
"4",
32+
"5",
33+
"6",
34+
"7",
35+
"8",
36+
"9",
37+
"10",
38+
"J",
39+
"Q",
40+
"K",
41+
];
2642
if (typeof card !== "string")
2743
throw new Error(`Invalid card format: "${card}". Expected a string.`);
2844

29-
let cardSuit = card.slice(-1);
30-
let cardRank = card.slice(0, -1);
31-
32-
if (validSuits.includes(cardSuit)) {
33-
switch (cardRank) {
34-
case "A":
35-
return 11;
36-
37-
case "J":
38-
case "Q":
39-
case "K":
40-
return 10;
41-
42-
case "2":
43-
case "3":
44-
case "4":
45-
case "5":
46-
case "6":
47-
case "7":
48-
case "8":
49-
case "9":
50-
case "10":
51-
return Number(cardRank);
52-
53-
default:
54-
throw new Error(
55-
`Invalid card format: "${card}" has an invalid rank "${cardRank}". Expected one of: A, 2–10, J, Q, K.`
56-
);
57-
}
58-
} else
45+
const cardSuit = card.slice(-1);
46+
const cardRank = card.slice(0, -1);
47+
48+
if (!validSuits.includes(cardSuit)) {
5949
throw new Error(
6050
`Invalid card format: "${card}" has an invalid suit "${cardSuit}". Expected one of: ♠, ♥, ♦, ♣.`
6151
);
52+
}
53+
if (!validRanks.includes(cardRank)) {
54+
throw new Error(
55+
`Invalid card format: "${card}" has an invalid rank "${cardSuit}". Expected one of: ♠, ♥, ♦, ♣.`
56+
);
57+
}
58+
59+
switch (cardRank) {
60+
case "A":
61+
return 11;
62+
63+
case "J":
64+
case "Q":
65+
case "K":
66+
return 10;
67+
68+
default:
69+
return Number(cardRank);
70+
}
6271
}
6372

6473
// The line below allows us to load the getCardValue function into tests in other files.

0 commit comments

Comments
 (0)