Skip to content

Commit 4ae7675

Browse files
committed
Refactor - to handle all valid cards and reject invalid ones
1 parent 7c3ddb9 commit 4ae7675

1 file changed

Lines changed: 15 additions & 13 deletions

File tree

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

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,24 @@
2424
// execute the code to ensure all tests pass.
2525

2626
export function getCardValue(card) {
27+
const rank = card.slice(0, -1);
2728
const suit = card.slice(-1);
28-
if (!["♠", "♥", "♦", "♣"].includes(suit)) {
29-
throw new Error(`Expected a number followed by a suit, but got "${card}"`);
29+
30+
const validSuits = ["♠", "♥", "♦", "♣"];
31+
const numberRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10"];
32+
const faceRanks = ["J", "Q", "K"];
33+
34+
if (!validSuits.includes(suit)) {
35+
throw new Error(`Expected a rank followed by a suit, but got "${card}"`);
3036
}
31-
if (card.slice(0, -1) === "A") {
37+
38+
if (rank === "A") {
3239
return 11;
33-
}
34-
if (card === "9♠") {
35-
return 9;
36-
} else if (card === "J♠" || card === "Q♥" || card === "K♦") {
40+
} else if (faceRanks.includes(rank)) {
3741
return 10;
38-
} else if (
39-
Number(card.slice(0, -1) >= 2 && Number(card.slice(0, -1) <= 10))
40-
) {
41-
return Number(card.slice(0, -1));
42-
} else {
43-
throw new Error(`Expected a number followed by a suit, but got "${card}"`);
42+
} else if (numberRanks.includes(rank)) {
43+
return Number(rank);
4444
}
45+
46+
throw new Error(`Expected a rank followed by a suit, but got "${card}"`);
4547
}

0 commit comments

Comments
 (0)