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 ) ;
26+ const suit = card . slice ( - 1 ) ;
27+
28+ if ( ! [ "♠" , "♥" , "♦" , "♣" ] . includes ( suit ) ) {
29+ throw new Error ( "Invalid card" ) ;
30+ }
31+
32+ if ( rank === "A" ) {
33+ return 11 ;
34+ }
35+
36+ if ( rank === "J" || rank === "Q" || rank === "K" ) {
37+ return 10 ;
38+ }
39+
40+ if ( [ "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" ] . includes ( rank ) ) {
41+ return Number ( rank ) ;
42+ }
43+
44+ throw new Error ( "Invalid card" ) ;
2645}
2746
2847// The line below allows us to load the getCardValue function into tests in other files.
@@ -37,18 +56,36 @@ function assertEquals(actualOutput, targetOutput) {
3756 ) ;
3857}
3958
40- // TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
41- // Examples:
59+ // Number cards
4260assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
61+ assertEquals ( getCardValue ( "10♥" ) , 10 ) ;
62+
63+ // Ace
64+ assertEquals ( getCardValue ( "A♣" ) , 11 ) ;
4365
44- // Handling invalid cards
66+ // Face cards
67+ assertEquals ( getCardValue ( "J♦" ) , 10 ) ;
68+ assertEquals ( getCardValue ( "Q♥" ) , 10 ) ;
69+ assertEquals ( getCardValue ( "K♠" ) , 10 ) ;
70+
71+ // Invalid cards
4572try {
4673 getCardValue ( "invalid" ) ;
47-
48- // This line will not be reached if an error is thrown as expected
4974 console . error ( "Error was not thrown for invalid card 😢" ) ;
5075} catch ( e ) {
5176 console . log ( "Error thrown for invalid card 🎉" ) ;
5277}
5378
54- // What other invalid card cases can you think of?
79+ try {
80+ getCardValue ( "1♠" ) ;
81+ console . error ( "Error was not thrown for invalid rank 😢" ) ;
82+ } catch ( e ) {
83+ console . log ( "Error thrown for invalid rank 🎉" ) ;
84+ }
85+
86+ try {
87+ getCardValue ( "AX" ) ;
88+ console . error ( "Error was not thrown for invalid suit 😢" ) ;
89+ } catch ( e ) {
90+ console . log ( "Error thrown for invalid suit 🎉" ) ;
91+ }
0 commit comments