|
22 | 22 | // execute the code to ensure all tests pass. |
23 | 23 |
|
24 | 24 | function getCardValue(card) { |
25 | | - const validSuits = ["♠", "♣", "♥", "♦"]; |
26 | | - |
27 | | - if (typeof card !== "string" || card.length < 2) { |
28 | | - throw new Error("Invalid card"); |
29 | | - } |
30 | | - |
31 | | - const suit = card.slice(-1); |
32 | 25 | const rank = card.slice(0, -1); |
33 | | - |
34 | | - if (!validSuits.includes(suit)) { |
35 | | - throw new Error("invalid card"); |
| 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)) { |
| 45 | + throw new Error("Invalid card"); |
36 | 46 | } |
37 | | - |
38 | 47 | if (rank === "A") { |
39 | 48 | return 11; |
40 | 49 | } |
41 | | - |
42 | 50 | if (rank === "J" || rank === "Q" || rank === "K") { |
43 | 51 | return 10; |
44 | 52 | } |
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"); |
| 53 | + return parseInt(rank); |
53 | 54 | } |
54 | 55 |
|
55 | | -module.exports = getCardValue; |
56 | | - |
57 | 56 | // The line below allows us to load the getCardValue function into tests in other files. |
58 | 57 | // 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 | +} |
61 | 67 |
|
62 | 68 | // TODO: Write tests to cover all outcomes, including throwing errors for invalid cards. |
63 | 69 | // Examples: |
| 70 | +assertEquals(getCardValue("9♠"), 9); |
64 | 71 |
|
65 | 72 | // Handling invalid cards |
| 73 | +try { |
| 74 | + getCardValue("invalid"); |
66 | 75 |
|
67 | | -// This line will not be reached if an error is thrown as expected |
| 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) {} |
68 | 79 |
|
69 | 80 | // What other invalid card cases can you think of? |
0 commit comments