Skip to content

Commit 984ec6c

Browse files
committed
complete code
1 parent 124ae45 commit 984ec6c

File tree

1 file changed

+54
-7
lines changed

1 file changed

+54
-7
lines changed

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

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

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

2843
// The line below allows us to load the getCardValue function into tests in other files.
2944
// This will be useful in the "rewrite tests with jest" step.
@@ -38,15 +53,47 @@ function assertEquals(actualOutput, targetOutput) {
3853
}
3954

4055
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
41-
// Examples:
56+
// Examples 1 numbers:
4257
assertEquals(getCardValue("9♠"), 9);
58+
assertEquals(getCardValue("5♣"), 5);
59+
60+
//Examples A:
61+
assertEquals(getCardValue("A♦"), 11)
62+
63+
//Examples J Q K:,
64+
assertEquals(getCardValue("Q♥"), 10)
65+
assertEquals(getCardValue("K♥"), 10)
4366

44-
// Handling invalid cards
45-
try {
46-
getCardValue("invalid");
67+
//Examples invalid numbers:
68+
assertThrow(()=>getCardValue("1♥"))
69+
assertThrow(()=>getCardValue("11♥"))
70+
71+
//Examples invalid suit:
72+
assertThrow(()=>getCardValue("A*"))
73+
74+
//Examples missing rank or suit:
75+
assertThrow(()=>getCardValue("♥"))
76+
assertThrow(()=>getCardValue("5"))
77+
78+
//Example extra suit:
79+
assertThrow(()=>getCardValue("Q♠♠"))
80+
81+
82+
function assertThrow(fn){
83+
try { (fn)
84+
// we try to run this function, if it throws, stop running this bit and run the catch below
4785

4886
// This line will not be reached if an error is thrown as expected
4987
console.error("Error was not thrown for invalid card");
50-
} catch (e) {}
88+
} catch (error) {
89+
// if the above code throws, we catch the error here, that stops the whole program crashing
90+
console.log('there was an error getting card value!',error)
91+
}}
92+
93+
console.log(' we finished running getcardvalue')
5194

5295
// What other invalid card cases can you think of?
96+
97+
//Examples wrong type:
98+
assertThrow(()=>getCardValue("null"))
99+
assertThrow(()=>getCardValue("42"))

0 commit comments

Comments
 (0)