2020// Acceptance criteria:
2121// After you have implemented the function, write tests to cover all the cases, and
2222// execute the code to ensure all tests pass.
23-
24- function getCardValue ( card ) {
25- // TODO: Implement this function
23+ function generateValidCards ( ) {
2624 const ranks = "A,2,3,4,5,6,7,8,9,10,J,Q,K" . split ( "," ) ;
2725 const suites = "♠,♥,♦,♣" . split ( "," ) ;
2826 const validCards = new Set ( ) ;
@@ -31,38 +29,47 @@ function getCardValue(card) {
3129 validCards . add ( rank + suite ) ;
3230 }
3331 }
32+ return validCards ;
33+ }
34+
35+ function getCardValue ( card ) {
36+ // TODO: Implement this function
37+ const validCards = generateValidCards ( ) ;
38+ if ( ! validCards . has ( card ) ) {
39+ throw new Error ( "invalid" ) ;
40+ }
41+
42+ let cardValue = card . slice ( 0 , - 1 ) ;
43+ if ( cardValue === "A" ) return 11 ;
44+ if ( cardValue === "J" || cardValue === "Q" || cardValue === "K" ) return 10 ;
45+ return Number ( cardValue ) ;
3446}
3547
3648// The line below allows us to load the getCardValue function into tests in other files.
3749// This will be useful in the "rewrite tests with jest" step.
3850module . exports = getCardValue ;
3951
4052// Helper functions to make our assertions easier to read.
41- function assertEquals ( actualOutput , targetOutput ) {
42- console . assert (
43- actualOutput === targetOutput ,
44- `Expected ${ actualOutput } to equal ${ targetOutput } `
45- ) ;
53+ function assertEquals ( card , targetOutput ) {
54+ try {
55+ const actualOutput = getCardValue ( card ) ;
56+ console . assert (
57+ actualOutput === targetOutput ,
58+ `Expected ${ actualOutput } to equal ${ targetOutput } `
59+ ) ;
60+ console . error ( "Error was not thrown for invalid card 😢" ) ;
61+ } catch ( e ) {
62+ console . log ( "Error thrown for invalid card 🎉" ) ;
63+ }
64+ console . log ( "-" . repeat ( 45 ) ) ;
4665}
4766
4867// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
49- // Examples:
50- assertEquals ( getCardValue ( "9♠" ) , 9 ) ;
51- assertEquals ( getCardValue ( "A" ) , 11 ) ;
52- assertEquals ( getCardValue ( "Q" ) , 10 ) ;
53- assertEquals ( getCardValue ( "5" ) , 5 ) ;
54- assertEquals ( getCardValue ( true ) , "invalid" ) ;
55- assertEquals ( getCardValue ( "A♠" ) , 11 ) ;
56- // assertEquals(getCardValue("invalid"), 9);
57-
58- // Handling invalid cards
59- try {
60- getCardValue ( "invalid" ) ;
61-
62- // This line will not be reached if an error is thrown as expected
63- console . error ( "Error was not thrown for invalid card 😢" ) ;
64- } catch ( e ) {
65- console . log ( "Error thrown for invalid card 🎉" ) ;
66- }
6768
68- // What other invalid card cases can you think of?
69+ assertEquals ( "9♠" , 9 ) ;
70+ assertEquals ( "A" , 11 ) ;
71+ assertEquals ( "Q" , 10 ) ;
72+ assertEquals ( "5" , 5 ) ;
73+ assertEquals ( "A♣" , 11 ) ;
74+ assertEquals ( "Q♣" , 11 ) ;
75+ assertEquals ( "A♦" , 10 ) ;
0 commit comments