Skip to content

Commit 9f2ebc3

Browse files
Implemented the function and wrote different test cases.
1 parent bc93560 commit 9f2ebc3

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

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

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,31 @@
2222
// execute the code to ensure all tests pass.
2323

2424
function getCardValue(card) {
25-
// TODO: Implement this function
25+
const suit = card.slice(-1);
26+
const rank = card.slice(0, -1);
27+
28+
if (suit !== "♠" && suit !== "♥" && suit !== "♦" && suit !== "♣") {
29+
throw new Error("Invalid card");
30+
}
31+
32+
if (rank === "A") {
33+
return 11;
34+
}
35+
36+
if (rank === "J" || rank === "Q" || rank === "K") {
37+
return 10;
38+
}
39+
40+
if (rank >= "2" && rank <= "10") {
41+
return Number(rank);
42+
}
43+
44+
throw new Error("Invalid card");
2645
}
2746

47+
// TODO: Implement this function
48+
49+
2850
// The line below allows us to load the getCardValue function into tests in other files.
2951
// This will be useful in the "rewrite tests with jest" step.
3052
module.exports = getCardValue;
@@ -40,6 +62,16 @@ function assertEquals(actualOutput, targetOutput) {
4062
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4163
// Examples:
4264
assertEquals(getCardValue("9♠"), 9);
65+
assertEquals(getCardValue("2♠"), 2);
66+
assertEquals(getCardValue("10♦"), 10);
67+
68+
// Face cards
69+
assertEquals(getCardValue("J♣"), 10);
70+
assertEquals(getCardValue("Q♥"), 10);
71+
assertEquals(getCardValue("K♦"), 10);
72+
73+
// Ace
74+
assertEquals(getCardValue("A♠"), 11);
4375

4476
// Handling invalid cards
4577
try {
@@ -49,4 +81,15 @@ try {
4981
console.error("Error was not thrown for invalid card");
5082
} catch (e) {}
5183

84+
5285
// What other invalid card cases can you think of?
86+
87+
const invalidCards = ["invalid", "1♠", "B♣", "10?", "Z♠"];
88+
for (const card of invalidCards) {
89+
try {
90+
getCardValue(card);
91+
console.error(`Error was not thrown for invalid card: ${card}`);
92+
} catch (e) {
93+
// Expected error, do nothing
94+
}
95+
}

0 commit comments

Comments
 (0)