2323
2424function getCardValue ( card ) {
2525 // TODO: Implement this function
26+ const rank = card . slice ( 0 , - 1 ) ;
27+ const suit = card . slice ( - 1 ) ;
28+
29+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
30+ const faceCards = [ "10" , "J" , "Q" , "K" ] ;
31+ const numberCards = [ "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" ] ;
32+
33+ if ( ! validSuits . includes ( suit ) ) {
34+ throw new Error ( "Invalid card suit" ) ;
35+ }
36+
37+ if ( rank === "A" ) return 11 ;
38+ if ( faceCards . includes ( rank ) ) return 10 ;
39+ if ( numberCards . includes ( rank ) ) return Number ( rank ) ;
40+
41+ throw new Error ( "Invalid card rank" ) ;
2642}
2743
2844// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,13 +56,30 @@ function assertEquals(actualOutput, targetOutput) {
4056// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4157// Examples:
4258assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
59+ assertEquals ( getCardValue ( "5♥" ) , 5 ) ;
60+ assertEquals ( getCardValue ( "K♦" ) , 10 ) ;
61+ assertEquals ( getCardValue ( "A♣" ) , 11 ) ;
4362
4463// Handling invalid cards
4564try {
4665 getCardValue ( "invalid" ) ;
66+ console . error ( "Error was not thrown for completely invalid card" ) ;
67+ } catch ( error ) { }
68+ try {
69+ getCardValue ( "1♠" ) ;
70+ console . error ( "Error was not thrown for invalid card rank" ) ;
71+ } catch ( error ) {
72+ assertEquals ( error . message , "Invalid card rank" ) ;
73+ }
4774
4875 // This line will not be reached if an error is thrown as expected
4976 console . error ( "Error was not thrown for invalid card" ) ;
5077} catch ( e ) { }
5178
5279// What other invalid card cases can you think of?
80+ try {
81+ getCardValue ( "5X" ) ;
82+ console . error ( "Error was not thrown for invalid card suit" ) ;
83+ } catch ( error ) {
84+ assertEquals ( error . message , "Invalid card suit" ) ;
85+ }
0 commit comments