Skip to content

Commit d28f26f

Browse files
committed
Implement getCardValue function to validate and return card values, including error handling for invalid cards
1 parent a9155fc commit d28f26f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,25 @@
2323

2424
function getCardValue(card) {
2525
// TODO: Implement this function
26+
const validRanks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
27+
const validSuits = ["♠", "♥", "♦", "♣"];
28+
29+
// Checking if the card is valid
30+
const rank = card.slice(0, -1);
31+
const suit = card.slice(-1);
32+
33+
if (!validRanks.includes(rank) || !validSuits.includes(suit)) {
34+
throw new Error("Invalid card");
35+
}
36+
37+
// Determininig the value of the card
38+
if (rank === "A") {
39+
return 11;
40+
} else if (["J", "Q", "K"].includes(rank)) {
41+
return 10;
42+
} else {
43+
return parseInt(rank, 10);
44+
}
2645
}
2746

2847
// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,6 +59,11 @@ function assertEquals(actualOutput, targetOutput) {
4059
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4160
// Examples:
4261
assertEquals(getCardValue("9♠"), 9);
62+
assertEquals(getCardValue("A♠"), 11);
63+
assertEquals(getCardValue("J♠"), 10);
64+
assertEquals(getCardValue("Q♠"), 10);
65+
assertEquals(getCardValue("K♠"), 10);
66+
4367

4468
// Handling invalid cards
4569
try {
@@ -52,3 +76,5 @@ try {
5276
}
5377

5478
// What other invalid card cases can you think of?
79+
assertEquals(getCardValue("11♥"), 11);
80+
assertEquals(getCardValue("A♦"), 11);

0 commit comments

Comments
 (0)