2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ const rank = card . slice ( 0 , - 1 ) ; // everything except the last character (suit)
26+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
27+ const suit = card . slice ( - 1 ) ;
28+
29+ if ( ! validSuits . includes ( suit ) ) {
30+ throw new Error ( "Invalid card" ) ;
31+ }
32+
33+ if ( rank === "A" ) {
34+ return 11 ;
35+ } else if ( rank === "J" || rank === "Q" || rank === "K" ) {
36+ return 10 ;
37+ } else if ( [ "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" ] . includes ( rank ) ) {
38+ return Number ( rank ) ;
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.
4662 getCardValue ( "invalid" ) ;
4763
4864 // This line will not be reached if an error is thrown as expected
49- console . error ( "Error was not thrown for invalid card 😢 " ) ;
65+ console . error ( "Error was not thrown for invalid card " ) ;
5066} catch ( e ) {
51- console . log ( "Error thrown for invalid card 🎉 " ) ;
67+ console . log ( "Error thrown for invalid card " ) ;
5268}
5369
70+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
71+ assertEquals ( getCardValue ( "J♣" ) , 10 ) ;
72+ assertEquals ( getCardValue ( "Q♦" ) , 10 ) ;
73+ assertEquals ( getCardValue ( "K♥" ) , 10 ) ;
74+ assertEquals ( getCardValue ( "2♠" ) , 2 ) ;
75+ assertEquals ( getCardValue ( "3♥" ) , 3 ) ;
76+
77+ // What other valid card cases can you think of?
78+ function assertEqual ( func , message ) {
79+ try {
80+ func ( ) ;
81+ console . log ( "Valid card test passed: " + message ) ;
82+ } catch ( e ) {
83+ console . error ( "Valid card test failed: " + message + " — " + e . message ) ;
84+ }
85+ }
5486// What other invalid card cases can you think of?
87+ function assertThrows ( func , errorMessage ) {
88+ try {
89+ func ( ) ;
90+ console . error ( "Error was not thrown " ) ;
91+ } catch ( e ) {
92+ if ( e . message === errorMessage ) {
93+ console . log ( "Error thrown as expected " ) ;
94+ } else {
95+ console . error ( `Unexpected error message: ${ e . message } ` ) ;
96+ }
97+ }
98+ }
0 commit comments