2323
2424function getCardValue ( card ) {
2525 // TODO: Implement this function
26+ const rank = card . slice ( 0 , - 1 ) ;
27+ const suit = card . slice ( - 1 ) ;
28+
29+ // Validate the suit
30+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
31+ if ( ! validSuits . includes ( suit ) ) {
32+ throw new Error ( "Invalid card: Invalid suit" ) ;
33+ }
34+
35+ if ( rank === "A" ) {
36+ return 11 ;
37+ } else if ( [ "J" , "Q" , "K" ] . includes ( rank ) ) {
38+ return 10 ;
39+ } else if ( [ "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" ] . includes ( rank ) ) {
40+ return Number ( rank ) ; // Convert the rank string to a number
41+ } else {
42+ throw new Error ( "Invalid card: Invalid rank" ) ;
43+ }
2644}
2745
2846// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,6 +58,9 @@ function assertEquals(actualOutput, targetOutput) {
4058// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4159// Examples:
4260assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
61+ assertEquals ( getCardValue ( "A♥" ) , 11 ) ;
62+ assertEquals ( getCardValue ( "Q♣" ) , 10 ) ;
63+ assertEquals ( getCardValue ( "K♠" ) , 10 ) ;
4364
4465// Handling invalid cards
4566try {
5071} catch ( e ) { }
5172
5273// What other invalid card cases can you think of?
74+ try {
75+ getCardValue ( "11♠" ) ;
76+
77+ // This line will not be reached if an error is thrown as expected
78+ console . error ( "Error was not thrown for invalid card" ) ;
79+ } catch ( e ) { }
80+
81+ try {
82+ getCardValue ( "A♤" ) ;
83+
84+ // This line will not be reached if an error is thrown as expected
85+ console . error ( "Error was not thrown for invalid card" ) ;
86+ } catch ( e ) { }
0 commit comments