2020// Acceptance criteria:
2121// After you have implemented the function, write tests to cover all the cases, and
2222// execute the code to ensure all tests pass.
23-
2423function getCardValue ( card ) {
25- // TODO: Implement this function
24+ // Validate input type
25+ if ( typeof card !== "string" ) {
26+ throw new Error ( "Card must be a string" ) ;
27+ }
28+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
29+ const validRanks = [ "A" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "J" , "Q" , "K" ] ;
30+ const suit = card . slice ( - 1 ) ;
31+ const rank = card . slice ( 0 , card . length - 1 ) ;
32+ if ( ! validSuits . includes ( suit ) || ! validRanks . includes ( rank ) ) {
33+ throw new Error ( `Invalid card format: ${ card } ` ) ;
34+ }
35+ if ( rank === "A" ) return 11 ;
36+ if ( [ "J" , "Q" , "K" ] . includes ( rank ) ) return 10 ;
37+ return parseInt ( rank , 10 ) ;
2638}
2739
2840// The line below allows us to load the getCardValue function into tests in other files.
@@ -39,8 +51,13 @@ function assertEquals(actualOutput, targetOutput) {
3951
4052// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4153// Examples:
54+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
55+ assertEquals ( getCardValue ( "2♥" ) , 2 ) ;
56+ assertEquals ( getCardValue ( "10♦" ) , 10 ) ;
57+ assertEquals ( getCardValue ( "J♣" ) , 10 ) ;
58+ assertEquals ( getCardValue ( "Q♠" ) , 10 ) ;
59+ assertEquals ( getCardValue ( "K♥" ) , 10 ) ;
4260assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
43-
4461// Handling invalid cards
4562try {
4663 getCardValue ( "invalid" ) ;
5067} catch ( e ) { }
5168
5269// What other invalid card cases can you think of?
70+ // "invalid", / not following format
71+ // "1♠", invalid rank
72+ // "11♣", invalid rank
73+ // "A", missing suit
74+ // "♠", missing rank
75+ // "A♦♦", invalid format
76+ // 5, not a string
77+ // "", empty string
0 commit comments