2222// execute the code to ensure all tests pass.
2323
2424function getCardValue ( card ) {
25- // TODO: Implement this function
25+ if ( typeof card !== "string" || card . length < 2 )
26+ {
27+ throw new Error ( "Invalid card" ) ;
28+ }
29+ const suit = card . slice ( - 1 ) ;
30+ const rank = card . slice ( 0 , - 1 ) ;
31+
32+ const validSuits = [ "♠" , "♥" , "♦" , "♣" ] ;
33+ const validRanks = [ "A" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "J" , "Q" , "K" ] ;
34+
35+ if ( ! validSuits . includes ( suit ) || ! validRanks . includes ( rank ) )
36+ {
37+ throw new Error ( "Invalid card" ) ;
38+ }
39+ else if ( rank == "A" )
40+ {
41+ return 11 ;
42+ }
43+ else if ( [ "J" , "Q" , "K" ] . includes ( rank ) )
44+ {
45+ return 10
46+ }
47+ else {
48+ return Number ( rank ) ;
49+ }
2650}
2751
2852// The line below allows us to load the getCardValue function into tests in other files.
2953// This will be useful in the "rewrite tests with jest" step.
30- module . exports = getCardValue ;
31-
54+ // module.exports = getCardValue;
55+ export default getCardValue ;
3256// Helper functions to make our assertions easier to read.
3357function assertEquals ( actualOutput , targetOutput ) {
3458 console . assert (
@@ -40,13 +64,40 @@ function assertEquals(actualOutput, targetOutput) {
4064// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
4165// Examples:
4266assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
67+ assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
68+ assertEquals ( getCardValue ( "K♦" ) , 10 ) ;
69+ assertEquals ( getCardValue ( "10♥" ) , 10 ) ;
4370
4471// Handling invalid cards
4572try {
46- getCardValue ( "invalid" ) ;
73+ getCardValue ( "11♠" ) ;
74+ console . error ( "Error was not thrown for invalid card" ) ;
75+ } catch ( e ) { }
76+ try {
77+ getCardValue ( "A?" ) ;
78+ console . error ( "Error was not thrown for invalid card" ) ;
79+ } catch ( e ) { }
80+ try {
81+ getCardValue ( "A" ) ;
4782
48- // This line will not be reached if an error is thrown as expected
83+
84+ console . error ( "Error was not thrown for invalid card" ) ;
85+ } catch ( e ) { }
86+ try {
87+ getCardValue ( "10" ) ;
88+
89+
4990 console . error ( "Error was not thrown for invalid card" ) ;
5091} catch ( e ) { }
5192
5293// What other invalid card cases can you think of?
94+ //try {
95+ //getCardValue("AA");
96+ //console.error("Error was not thrown for invalid card");
97+ //} catch (e) {}
98+ //try {
99+ //getCardValue("1♠");
100+
101+
102+ //console.error("Error was not thrown for invalid card");
103+ //} catch (e) {}
0 commit comments