|
22 | 22 | // execute the code to ensure all tests pass. |
23 | 23 |
|
24 | 24 | function getCardValue(card) { |
25 | | - const rank = card.slice(0, -1); |
26 | | - const suit = card.slice(-1); |
27 | | - const validSuits = ["♠", "♥", "♦", "♣"]; |
28 | | - const validRanks = [ |
29 | | - "A", |
30 | | - "2", |
31 | | - "3", |
32 | | - "4", |
33 | | - "5", |
34 | | - "6", |
35 | | - "7", |
36 | | - "8", |
37 | | - "9", |
38 | | - "10", |
39 | | - "J", |
40 | | - "Q", |
41 | | - "K", |
42 | | - ]; |
43 | | - |
44 | | - if (!validSuits.includes(suit) || !validRanks.includes(rank)) { |
| 25 | + const validSuits = ["♠", "♣", "♥", "♦"]; |
| 26 | + |
| 27 | + if (typeof card !== "string" || card.length < 2) { |
45 | 28 | throw new Error("Invalid card"); |
46 | 29 | } |
| 30 | + |
| 31 | + const suit = card.slice(-1); |
| 32 | + const rank = card.slice(0, -1); |
| 33 | + |
| 34 | + if (!validSuits.includes(suit)) { |
| 35 | + throw new Error("invalid card"); |
| 36 | + } |
| 37 | + |
47 | 38 | if (rank === "A") { |
48 | 39 | return 11; |
49 | 40 | } |
| 41 | + |
50 | 42 | if (rank === "J" || rank === "Q" || rank === "K") { |
51 | 43 | return 10; |
52 | 44 | } |
53 | | - return parseInt(rank); |
| 45 | + |
| 46 | + const numberValue = Number(rank); |
| 47 | + |
| 48 | + if (!Number.isNaN(numberValue) && numberValue >= 2 && numberValue <= 10) { |
| 49 | + return numberValue; |
| 50 | + } |
| 51 | + |
| 52 | + throw new Error("Invalid card"); |
54 | 53 | } |
55 | 54 |
|
| 55 | +module.exports = getCardValue; |
| 56 | + |
56 | 57 | // The line below allows us to load the getCardValue function into tests in other files. |
57 | 58 | // This will be useful in the "rewrite tests with jest" step. |
58 | | -module.exports = getCardValue; |
59 | 59 |
|
60 | 60 | // Helper functions to make our assertions easier to read. |
61 | | -function assertEquals(actualOutput, targetOutput) { |
62 | | - console.assert( |
63 | | - actualOutput === targetOutput, |
64 | | - `Expected ${actualOutput} to equal ${targetOutput}` |
65 | | - ); |
66 | | -} |
67 | 61 |
|
68 | 62 | // TODO: Write tests to cover all outcomes, including throwing errors for invalid cards. |
69 | 63 | // Examples: |
70 | | -assertEquals(getCardValue("9♠"), 9); |
71 | 64 |
|
72 | 65 | // Handling invalid cards |
73 | | -try { |
74 | | - getCardValue("invalid"); |
75 | 66 |
|
76 | | - // This line will not be reached if an error is thrown as expected |
77 | | - console.error("Error was not thrown for invalid card"); |
78 | | -} catch (e) {} |
| 67 | +// This line will not be reached if an error is thrown as expected |
79 | 68 |
|
80 | 69 | // What other invalid card cases can you think of? |
0 commit comments