2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ const suit = card [ card . length - 1 ] ;
26+ const rank = card . slice ( 0 , card . length - 1 ) ;
27+ const numericValue = Number ( rank ) ;
28+
29+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
30+
31+ if ( ! validSuits . includes ( suit ) ) {
32+ throw new Error ( "Invalid card" ) ;
33+ } else if ( rank === "A" ) {
34+ return 11 ;
35+ } else if ( rank === "J" || rank === "Q" || rank === "K" ) {
36+ return 10 ;
37+ } else if ( numericValue >= 2 && numericValue <= 10 ) {
38+ return numericValue ;
39+ } else {
40+ throw new Error ( "Invalid card" ) ;
41+ }
2642}
2743
2844// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,6 +56,12 @@ function assertEquals(actualOutput, targetOutput) {
4056// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4157// Examples:
4258assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
59+ assertEquals ( getCardValue ( "A♣" ) , 11 ) ;
60+ assertEquals ( getCardValue ( "J♦" ) , 10 ) ;
61+ assertEquals ( getCardValue ( "10♥" ) , 10 ) ;
62+ assertEquals ( getCardValue ( "Q♦" ) , 10 ) ;
63+ assertEquals ( getCardValue ( "K♦" ) , 10 ) ;
64+ assertEquals ( getCardValue ( "2♥" ) , 2 ) ;
4365
4466// Handling invalid cards
4567try {
5274}
5375
5476// What other invalid card cases can you think of?
77+ try {
78+ getCardValue ( "1♠" ) ;
79+ console . error ( "Error was not thrown for invalid card 😢" ) ;
80+ } catch {
81+ console . log ( "Error thrown for invalid card 🎉" ) ;
82+ }
83+ try {
84+ getCardValue ( "10X" ) ;
85+ console . error ( "Error was not thrown for invalid card 😢" ) ;
86+ } catch {
87+ console . log ( "Error thrown for invalid card 🎉" ) ;
88+ }
89+ try {
90+ getCardValue ( "♠A" ) ;
91+ console . error ( "Error was not thrown for invalid card 😢" ) ;
92+ } catch {
93+ console . log ( "Error thrown for invalid card 🎉" ) ;
94+ }
95+ try {
96+ getCardValue ( "10♠♠" ) ;
97+ console . error ( "Error was not thrown for invalid card 😢" ) ;
98+ } catch {
99+ console . log ( "Error thrown for invalid card 🎉" ) ;
100+ }
0 commit comments