2323
2424function getCardValue ( card ) {
2525 // TODO: Implement this function
26+ if ( typeof card !== "string" ) {
27+ throw new Error ( "Card must be a string" ) ;
28+ }
29+
30+ const rank = card . slice ( 0 , - 1 ) ;
31+ const suit = card . slice ( - 1 ) ;
32+
33+ const validRanks = [ "A" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "J" , "Q" , "K" ] ;
34+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
35+
36+ if ( ! validRanks . includes ( rank ) || ! validSuits . includes ( suit ) ) {
37+ throw new Error ( "Invalid card format" ) ;
38+ }
39+
40+ if ( rank === "A" ) {
41+ return 11 ;
42+ } else if ( [ "J" , "Q" , "K" ] . includes ( rank ) ) {
43+ return 10 ;
44+ } else {
45+ return parseInt ( rank , 10 ) ;
46+ }
2647}
2748
2849// The line below allows us to load the getCardValue function into tests in other files.
@@ -39,14 +60,31 @@ function assertEquals(actualOutput, targetOutput) {
3960
4061// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4162// Examples:
42- assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
63+ assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
64+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
65+ assertEquals ( getCardValue ( "J♠" ) , 10 ) ;
4366
4467// Handling invalid cards
4568try {
46- getCardValue ( "invalid" ) ;
69+ getCardValue ( "invalid" ) ;
4770
4871 // This line will not be reached if an error is thrown as expected
4972 console . error ( "Error was not thrown for invalid card" ) ;
5073} catch ( e ) { }
5174
5275// What other invalid card cases can you think of?
76+ try {
77+ getCardValue ( "11♠" ) ;
78+ console . error ( "Error was not thrown for invalid rank" ) ;
79+ } catch ( e ) { }
80+
81+ try {
82+ getCardValue ( "A♤" ) ;
83+ console . error ( "Error was not thrown for invalid suit" ) ;
84+ } catch ( e ) { }
85+
86+ try {
87+ getCardValue ( 123 ) ;
88+ console . error ( "Error was not thrown for non-string input" ) ;
89+ } catch ( e ) { }
90+
0 commit comments