2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ if ( typeof card !== "string" || card . length < 2 ) {
26+ throw new Error ( "Error: Invalid card format" ) ;
27+ }
28+
29+ const rank = card . slice ( 0 , - 1 ) ;
30+ const suit = card . slice ( - 1 ) ;
31+
32+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
33+ if ( ! validSuits . includes ( suit ) ) {
34+ throw new Error ( "Error: Invalid suit" ) ;
35+ }
36+
37+ switch ( rank ) {
38+ case "A" :
39+ return 11 ;
40+ case "J" :
41+ case "Q" :
42+ case "K" :
43+ return 10 ;
44+ case "2" :
45+ return 2 ;
46+ case "3" :
47+ return 3 ;
48+ case "4" :
49+ return 4 ;
50+ case "5" :
51+ return 5 ;
52+ case "6" :
53+ return 6 ;
54+ case "7" :
55+ return 7 ;
56+ case "8" :
57+ return 8 ;
58+ case "9" :
59+ return 9 ;
60+ case "10" :
61+ return 10 ;
62+
63+ default :
64+ throw new Error ( "Error: Invalid card format" ) ;
2665}
2766
67+ }
2868// The line below allows us to load the getCardValue function into tests in other files.
2969// This will be useful in the "rewrite tests with jest" step.
3070module . exports = getCardValue ;
@@ -40,8 +80,13 @@ function assertEquals(actualOutput, targetOutput) {
4080// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4181// Examples:
4282assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
83+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
84+ assertEquals ( getCardValue ( "J♣" ) , 10 ) ;
85+ assertEquals ( getCardValue ( "Q♦" ) , 10 ) ;
86+ assertEquals ( getCardValue ( "K♥" ) , 10 ) ;
87+ assertEquals ( getCardValue ( "2♥" ) , 2 ) ;
88+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
4389
44- // Handling invalid cards
4590try {
4691 getCardValue ( "invalid" ) ;
4792
5297}
5398
5499// What other invalid card cases can you think of?
100+ // A) 1♠, 11♠, AA♠, ♠♠, 10
0 commit comments