Skip to content

Commit 8d6eb95

Browse files
committed
Implement getCardValue function with test cases for number, face, ace, and invalid cards
1 parent 0cba6bb commit 8d6eb95

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

Sprint-3/1-key-implement/3-get-card-value.js

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,26 @@
88
// write one test at a time, and make it pass, build your solution up methodically
99
// just make one change at a time -- don't rush -- programmers are deep and careful thinkers
1010
function getCardValue(card) {
11-
if (rank === "A") return 11;
11+
const rank = card.slice(0, -1); // get the rank (before the suit symbol)
12+
13+
if (!isNaN(rank)) {
14+
return Number(rank); // Number card
15+
}
16+
17+
if (rank === "J" || rank === "Q" || rank === "K") {
18+
return 10; // Face cards
19+
}
20+
21+
if (rank === "A") {
22+
return 11; // Ace
23+
}
24+
25+
// Anything else is invalid
26+
throw new Error("Invalid card rank");
1227
}
1328

29+
// if the rank is not a number or a face card, throw an error(invalid card rank).
30+
1431
// You need to write assertions for your function to check it works in different cases
1532
// we're going to use this helper function to make our assertions easier to read
1633
// if the actual output matches the target output, the test will pass
@@ -33,13 +50,23 @@ assertEquals(aceofSpades, 11);
3350
// When the function is called with such a card,
3451
// Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5).
3552
const fiveofHearts = getCardValue("5♥");
36-
// ====> write your test here, and then add a line to pass the test in the function above
53+
assertEquals(fiveofHearts, 5);
54+
55+
const tenofDiamonds = getCardValue("10♦");
56+
assertEquals(tenofDiamonds, 10);
3757

3858
// Handle Face Cards (J, Q, K):
3959
// Given a card with a rank of "10," "J," "Q," or "K",
4060
// When the function is called with such a card,
4161
// Then it should return the value 10, as these cards are worth 10 points each in blackjack.
62+
const jackofClubs = getCardValue("J♣");
63+
assertEquals(jackofClubs, 10);
4264

65+
const queenofHearts = getCardValue("Q♥");
66+
assertEquals(queenofHearts, 10);
67+
68+
const kingofSpades = getCardValue("K♠");
69+
assertEquals(kingofSpades, 10);
4370
// Handle Ace (A):
4471
// Given a card with a rank of "A",
4572
// When the function is called with an Ace,
@@ -49,3 +76,8 @@ const fiveofHearts = getCardValue("5♥");
4976
// Given a card with an invalid rank (neither a number nor a recognized face card),
5077
// When the function is called with such a card,
5178
// Then it should throw an error indicating "Invalid card rank."
79+
try {
80+
getCardValue("Z♠");
81+
} catch (error) {
82+
console.log("Caught error:", error.message); // Should say "Invalid card rank"
83+
}

0 commit comments

Comments
 (0)