Skip to content

Commit 3441cd5

Browse files
committed
complete code
1 parent 3372770 commit 3441cd5

File tree

1 file changed

+51
-7
lines changed

1 file changed

+51
-7
lines changed

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

Lines changed: 51 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,44 @@ 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:
57+
// Examples 1 numbers:
4258
assertEquals(getCardValue("9♠"), 9);
59+
assertEquals(getCardValue("5♣"), 5);
60+
61+
//Examples A:
62+
assertEquals(getCardValue("A♦"), 11)
4363

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

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

5296
// What other invalid card cases can you think of?

0 commit comments

Comments
 (0)