2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ const validRanks = [
26+ "A" ,
27+ "2" ,
28+ "3" ,
29+ "4" ,
30+ "5" ,
31+ "6" ,
32+ "7" ,
33+ "8" ,
34+ "9" ,
35+ "10" ,
36+ "J" ,
37+ "Q" ,
38+ "K" ,
39+ ] ;
40+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
41+
42+ if ( typeof card !== "string" ) {
43+ throw new Error ( "Invalid card" ) ;
44+ }
45+
46+ if ( card . length < 2 ) {
47+ throw new Error ( "Invalid card" ) ;
48+ }
49+
50+ const rank = card . substring ( 0 , card . length - 1 ) ;
51+ const suit = card . substring ( card . length - 1 ) ;
52+
53+ if ( ! validRanks . includes ( rank ) ) {
54+ throw new Error ( "Invalid card" ) ;
55+ }
56+
57+ if ( ! validSuits . includes ( suit ) ) {
58+ throw new Error ( "Invalid card" ) ;
59+ }
60+
61+ if ( rank === "A" ) {
62+ return 11 ;
63+ } else if ( rank === "J" || rank === "Q" || rank === "K" ) {
64+ return 10 ;
65+ } else {
66+ return parseInt ( rank ) ;
67+ }
2668}
2769
2870// The line below allows us to load the getCardValue function into tests in other files.
@@ -40,7 +82,10 @@ function assertEquals(actualOutput, targetOutput) {
4082// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4183// Examples:
4284assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
43-
85+ assertEquals ( getCardValue ( "A♥" ) , 11 ) ;
86+ assertEquals ( getCardValue ( "J♦" ) , 10 ) ;
87+ assertEquals ( getCardValue ( "Q♣" ) , 10 ) ;
88+ assertEquals ( getCardValue ( "K♦" ) , 10 ) ;
4489// Handling invalid cards
4590try {
4691 getCardValue ( "invalid" ) ;
5095} catch ( e ) { }
5196
5297// What other invalid card cases can you think of?
98+ assertEquals ( getCardValue ( "A♣" ) , 11 ) ;
99+ assertEquals ( getCardValue ( "J♥" ) , 10 ) ;
100+ assertEquals ( getCardValue ( "Q♦" ) , 10 ) ;
101+ assertEquals ( getCardValue ( "K♠" ) , 10 ) ;
102+
103+ try {
104+ getCardValue ( "A" ) ;
105+ console . error ( "Error was not thrown for invalid card" ) ;
106+ } catch ( e ) { }
107+
108+ try {
109+ getCardValue ( "invalid" ) ;
110+ console . error ( "Error was not thrown for invalid card" ) ;
111+ } catch ( e ) { }
112+
113+ try {
114+ getCardValue ( "2♠♣" ) ;
115+ console . error ( "Error was not thrown for invalid card" ) ;
116+ } catch ( e ) { }
0 commit comments