2323
2424function getCardValue ( card ) {
2525 // Handling invalid cards
26- try {
27- const rank = card . slice ( 0 , - 1 ) ; //rank of the card is everything except the last character of card string
28- const suit = card . slice ( - 1 ) ; // suit is the last character of the card string
29- if ( ! isValidCard ( rank , suit ) ) {
30- throw new Error ( "Invalid card" ) ;
31- }
32- if ( rank === "J" || rank === "Q" || rank == "K" ) return 10 ;
33- else if ( rank == "A" ) return 11 ;
34- else return Number ( rank ) ;
35- } catch ( e ) {
36- return e . message ;
37- }
26+ const rank = card . slice ( 0 , - 1 ) ; //rank of the card is everything except the last character of card string
27+ const suit = card . slice ( - 1 ) ; // suit is the last character of the card string
28+ if ( ! isValidCard ( rank , suit ) ) throw new Error ( "Invalid card" ) ;
29+ if ( rank === "J" || rank === "Q" || rank == "K" ) return 10 ;
30+ else if ( rank == "A" ) return 11 ;
31+ else return Number ( rank ) ;
3832}
3933
4034function isValidCard ( rank , suit ) {
@@ -70,6 +64,15 @@ function assertEquals(actualOutput, targetOutput) {
7064 ) ;
7165}
7266
67+ function assertThrows ( fnGetCardValue ) {
68+ try {
69+ fnGetCardValue ( ) ; // run the function
70+ console . assert ( false , "Expected function to throw an error" ) ;
71+ } catch ( err ) {
72+ console . assert ( err instanceof Error , "Expected an Error to be thrown" ) ;
73+ }
74+ }
75+
7376// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
7477// Examples:
7578assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
@@ -79,8 +82,11 @@ assertEquals(getCardValue("A♣"), 11);
7982assertEquals ( getCardValue ( "2♠" ) , 2 ) ;
8083assertEquals ( getCardValue ( "J♦" ) , 10 ) ;
8184assertEquals ( getCardValue ( "K♠" ) , 10 ) ;
82- assertEquals ( getCardValue ( "Invalid" ) , "Invalid card" ) ;
83- assertEquals ( getCardValue ( "1Q" ) , "Invalid card" ) ;
84- assertEquals ( getCardValue ( "-10♦" ) , "Invalid card" ) ;
85- assertEquals ( getCardValue ( "♦K" ) , "Invalid card" ) ;
86- assertEquals ( getCardValue ( "Q♦♦" ) , "Invalid card" ) ;
85+
86+ // using function wrapper in the below lines of code so instead of passing teh result of function I can pass the function here,
87+ // and it is being called in try block of assertThrows function
88+ assertThrows ( ( ) => getCardValue ( "Invalid" ) ) ;
89+ assertThrows ( ( ) => getCardValue ( "1Q" ) ) ;
90+ assertThrows ( ( ) => getCardValue ( "-10♦" ) ) ;
91+ assertThrows ( ( ) => getCardValue ( "♦K" ) ) ;
92+ assertThrows ( ( ) => getCardValue ( "Q♦♦" ) ) ;
0 commit comments