2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ let rank = card . slice ( 0 , - 1 ) ;
26+ let suit = card . slice ( - 1 ) ;
27+ const suitArray = [ "♠" , "♥" , "♦" , "♣" ] ;
28+ if ( ! suitArray . includes ( suit ) ) throw new Error ( "Invalid card" ) ;
29+ if ( rank === "A" ) return 11 ;
30+ if ( rank === "Q" || rank === "K" || rank === "J" ) return 10 ;
31+ if ( Number ( rank ) >= 2 && Number ( rank ) <= 10 ) return Number ( rank ) ;
32+ throw new Error ( "Invalid card" ) ;
2633}
2734
2835// The line below allows us to load the getCardValue function into tests in other files.
@@ -39,13 +46,37 @@ function assertEquals(actualOutput, targetOutput) {
3946
4047// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4148// Examples:
42- assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
49+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
50+ assertEquals ( getCardValue ( "A♣" ) , 11 ) ;
51+ assertEquals ( getCardValue ( "Q♠" ) , 10 ) ;
52+ assertEquals ( getCardValue ( "K♣" ) , 10 ) ;
53+ assertEquals ( getCardValue ( "J♦" ) , 10 ) ;
54+ assertEquals ( getCardValue ( "2♠" ) , 2 ) ;
55+ assertEquals ( getCardValue ( "10♣" ) , 10 ) ;
4356
4457// Handling invalid cards
4558try {
46- getCardValue ( "invalid" ) ;
59+ getCardValue ( "AX" ) ;
60+ console . error ( "Error was not thrown for invalid card 😢" ) ;
61+ } catch ( e ) {
62+ console . log ( "Error thrown for invalid card 🎉" ) ;
63+ }
64+ try {
65+ getCardValue ( "B♣" ) ;
66+ console . error ( "Error was not thrown for invalid card 😢" ) ;
67+ } catch ( e ) {
68+ console . log ( "Error thrown for invalid card 🎉" ) ;
69+ }
70+
71+ try {
72+ getCardValue ( "1♦" ) ;
73+ console . error ( "Error was not thrown for invalid card 😢" ) ;
74+ } catch ( e ) {
75+ console . log ( "Error thrown for invalid card 🎉" ) ;
76+ }
4777
48- // This line will not be reached if an error is thrown as expected
78+ try {
79+ getCardValue ( "11♣" ) ;
4980 console . error ( "Error was not thrown for invalid card 😢" ) ;
5081} catch ( e ) {
5182 console . log ( "Error thrown for invalid card 🎉" ) ;
0 commit comments