2323
2424function getCardValue ( card ) {
2525 // TODO: Implement this function
26+ const validRanks = [ "A" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "J" , "Q" , "K" ] ;
27+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
28+
29+ // Checking if the card is valid
30+ const rank = card . slice ( 0 , - 1 ) ;
31+ const suit = card . slice ( - 1 ) ;
32+
33+ if ( ! validRanks . includes ( rank ) || ! validSuits . includes ( suit ) ) {
34+ throw new Error ( "Invalid card" ) ;
35+ }
36+
37+ // Determininig the value of the card
38+ if ( rank === "A" ) {
39+ return 11 ;
40+ } else if ( [ "J" , "Q" , "K" ] . includes ( rank ) ) {
41+ return 10 ;
42+ } else {
43+ return parseInt ( rank , 10 ) ;
44+ }
2645}
2746
2847// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,6 +59,11 @@ function assertEquals(actualOutput, targetOutput) {
4059// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4160// Examples:
4261assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
62+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
63+ assertEquals ( getCardValue ( "J♠" ) , 10 ) ;
64+ assertEquals ( getCardValue ( "Q♠" ) , 10 ) ;
65+ assertEquals ( getCardValue ( "K♠" ) , 10 ) ;
66+
4367
4468// Handling invalid cards
4569try {
5276}
5377
5478// What other invalid card cases can you think of?
79+ assertEquals ( getCardValue ( "11♥" ) , 11 ) ;
80+ assertEquals ( getCardValue ( "A♦" ) , 11 ) ;
0 commit comments