Skip to content

Commit 63d362f

Browse files
committed
Implement getCardValue and add console.assert tests
1 parent e2d0678 commit 63d362f

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

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

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

2424
function getCardValue(card) {
25-
// TODO: Implement this function
25+
const validSuits = ["♠", "♥", "♦", "♣"];
26+
const validRanks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
27+
28+
if (typeof card !== "string" || card.length < 2) {
29+
throw new Error("Invalid card");
30+
}
31+
32+
const suit = card.slice(-1);
33+
const rank = card.slice(0, -1);
34+
35+
if (!validSuits.includes(suit) || !validRanks.includes(rank)) {
36+
throw new Error("Invalid card");
37+
}
38+
39+
if (rank === "A") return 11;
40+
if (rank === "J" || rank === "Q" || rank === "K") return 10;
41+
42+
return Number(rank);
2643
}
2744

45+
2846
// The line below allows us to load the getCardValue function into tests in other files.
2947
// This will be useful in the "rewrite tests with jest" step.
3048
module.exports = getCardValue;
@@ -50,3 +68,24 @@ try {
5068
} catch (e) {}
5169

5270
// What other invalid card cases can you think of?
71+
// Number cards
72+
assertEquals(getCardValue("2♠"), 2);
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);
82+
83+
// More invalid cases
84+
const invalidCards = ["", "A", "11♠", "1♠", "B♠", "10X", "♠A"];
85+
86+
for (const bad of invalidCards) {
87+
try {
88+
getCardValue(bad);
89+
console.error("Error was not thrown for invalid card:", bad);
90+
} catch (e) {}
91+
}

0 commit comments

Comments
 (0)