2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ const suit = card . slice ( - 1 ) ;
26+ const rank = card . slice ( 0 , - 1 ) ;
27+
28+ if ( suit !== "♠" && suit !== "♥" && suit !== "♦" && 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 ( rank >= "2" && rank <= "10" ) {
41+ return Number ( rank ) ;
42+ }
43+
44+ throw new Error ( "Invalid card" ) ;
2645}
2746
47+ // TODO: Implement this function
48+
49+
2850// The line below allows us to load the getCardValue function into tests in other files.
2951// This will be useful in the "rewrite tests with jest" step.
3052module . exports = getCardValue ;
@@ -40,6 +62,16 @@ function assertEquals(actualOutput, targetOutput) {
4062// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4163// Examples:
4264assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
65+ assertEquals ( getCardValue ( "2♠" ) , 2 ) ;
66+ assertEquals ( getCardValue ( "10♦" ) , 10 ) ;
67+
68+ // Face cards
69+ assertEquals ( getCardValue ( "J♣" ) , 10 ) ;
70+ assertEquals ( getCardValue ( "Q♥" ) , 10 ) ;
71+ assertEquals ( getCardValue ( "K♦" ) , 10 ) ;
72+
73+ // Ace
74+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
4375
4476// Handling invalid cards
4577try {
4981 console . error ( "Error was not thrown for invalid card" ) ;
5082} catch ( e ) { }
5183
84+
5285// What other invalid card cases can you think of?
86+
87+ const invalidCards = [ "invalid" , "1♠" , "B♣" , "10?" , "Z♠" ] ;
88+ for ( const card of invalidCards ) {
89+ try {
90+ getCardValue ( card ) ;
91+ console . error ( `Error was not thrown for invalid card: ${ card } ` ) ;
92+ } catch ( e ) {
93+ // Expected error, do nothing
94+ }
95+ }
0 commit comments