Skip to content

Commit 433a848

Browse files
committed
Implement getCardValue and add assertion tests for valid and invalid cards
1 parent 2c53190 commit 433a848

File tree

1 file changed

+59
-4
lines changed

1 file changed

+59
-4
lines changed

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

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,35 @@
2222
// execute the code to ensure all tests pass.
2323

2424
function getCardValue(card) {
25-
// TODO: Implement this function
25+
const suits = ["♠", "♥", "♦", "♣"];
26+
27+
// Card must be a string
28+
if (typeof card !== "string") {
29+
throw new Error("Invalid card");
30+
}
31+
32+
const suit = card.slice(-1);
33+
const rank = card.slice(0, -1);
34+
35+
if (!suits.includes(suit)) {
36+
throw new Error("Invalid card");
37+
}
38+
39+
if (rank === "A") {
40+
return 11;
41+
}
42+
43+
if (["J", "Q", "K"].includes(rank)) {
44+
return 10;
45+
}
46+
47+
const number = Number(rank);
48+
49+
if (number >= 2 && number <= 10) {
50+
return number;
51+
}
52+
53+
throw new Error("Invalid card");
2654
}
2755

2856
// The line below allows us to load the getCardValue function into tests in other files.
@@ -38,15 +66,42 @@ function assertEquals(actualOutput, targetOutput) {
3866
}
3967

4068
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
41-
// Examples:
69+
70+
// Number cards
71+
assertEquals(getCardValue("2♠"), 2);
4272
assertEquals(getCardValue("9♠"), 9);
73+
assertEquals(getCardValue("10♥"), 10);
74+
75+
// Face cards
76+
assertEquals(getCardValue("J♣"), 10);
77+
assertEquals(getCardValue("Q♦"), 10);
78+
assertEquals(getCardValue("K♦"), 10);
79+
80+
// Ace
81+
assertEquals(getCardValue("A♠"), 11);
4382

4483
// Handling invalid cards
4584
try {
4685
getCardValue("invalid");
86+
console.error("Error was not thrown for invalid card");
87+
} catch (e) {}
88+
89+
try {
90+
getCardValue("1♠");
91+
console.error("Error was not thrown for invalid card");
92+
} catch (e) {}
93+
94+
try {
95+
getCardValue("11♠");
96+
console.error("Error was not thrown for invalid card");
97+
} catch (e) {}
4798

48-
// This line will not be reached if an error is thrown as expected
99+
try {
100+
getCardValue("A");
49101
console.error("Error was not thrown for invalid card");
50102
} catch (e) {}
51103

52-
// What other invalid card cases can you think of?
104+
try {
105+
getCardValue("♠");
106+
console.error("Error was not thrown for invalid card");
107+
} catch (e) {}

0 commit comments

Comments
 (0)