Skip to content

Commit d6e6eb8

Browse files
committed
Add card value function + tests
1 parent 6a32e82 commit d6e6eb8

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

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

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

2424
function getCardValue(card) {
2525
// TODO: Implement this function
26+
const validRanks = [
27+
"A",
28+
"2",
29+
"3",
30+
"4",
31+
"5",
32+
"6",
33+
"7",
34+
"8",
35+
"9",
36+
"10",
37+
"J",
38+
"Q",
39+
"K",
40+
];
41+
const validSuits = ["♠", "♥", "♦", "♣"];
42+
43+
// Suit is always the last character
44+
const suit = card.slice(-1);
45+
46+
// Rank is everything before the suit
47+
const rank = card.slice(0, -1);
48+
49+
// Validate rank and suit
50+
if (!validRanks.includes(rank) || !validSuits.includes(suit)) {
51+
throw new Error("Invalid card");
52+
}
53+
54+
// Convert rank to value
55+
if (rank === "A") return 11;
56+
if (["J", "Q", "K"].includes(rank)) return 10;
57+
58+
// Number card
59+
return Number(rank);
2660
}
2761

2862
// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,6 +74,12 @@ function assertEquals(actualOutput, targetOutput) {
4074
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4175
// Examples:
4276
assertEquals(getCardValue("9♠"), 9);
77+
assertEquals(getCardValue("A♣"), 11);
78+
assertEquals(getCardValue("J♦"), 10);
79+
assertEquals(getCardValue("Q♥"), 10);
80+
assertEquals(getCardValue("K♠"), 10);
81+
assertEquals(getCardValue("2♠"), 2);
82+
assertEquals(getCardValue("10♦"), 10);
4383

4484
// Handling invalid cards
4585
try {
@@ -52,3 +92,30 @@ try {
5292
}
5393

5494
// What other invalid card cases can you think of?
95+
try {
96+
getCardValue("1♠"); // invalid rank
97+
console.error("Error was not thrown for invalid rank");
98+
} catch (e) {
99+
console.log("Error thrown for invalid rank 🎉");
100+
}
101+
102+
try {
103+
getCardValue("A?"); // invalid suit
104+
console.error("Error was not thrown for invalid suit");
105+
} catch (e) {
106+
console.log("Error thrown for invalid suit 🎉");
107+
}
108+
109+
try {
110+
getCardValue("10"); // missing suit
111+
console.error("Error was not thrown for missing suit");
112+
} catch (e) {
113+
console.log("Error thrown for missing suit 🎉");
114+
}
115+
116+
try {
117+
getCardValue(""); // empty string
118+
console.error("Error was not thrown for empty string");
119+
} catch (e) {
120+
console.log("Error thrown for empty string 🎉");
121+
}

0 commit comments

Comments
 (0)