|
22 | 22 | // execute the code to ensure all tests pass. |
23 | 23 |
|
24 | 24 | function getCardValue(card) { |
25 | | - // TODO: Implement this function |
| 25 | + const validSuits = ["♠", "♥", "♦", "♣"]; |
| 26 | + const validRanks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; |
| 27 | + |
| 28 | + if (typeof card !== "string" || card.length < 2) { |
| 29 | + throw new Error("Invalid card"); |
| 30 | + } |
| 31 | + |
| 32 | + const suit = card.slice(-1); |
| 33 | + const rank = card.slice(0, -1); |
| 34 | + |
| 35 | + if (!validSuits.includes(suit) || !validRanks.includes(rank)) { |
| 36 | + throw new Error("Invalid card"); |
| 37 | + } |
| 38 | + |
| 39 | + if (rank === "A") return 11; |
| 40 | + if (rank === "J" || rank === "Q" || rank === "K") return 10; |
| 41 | + |
| 42 | + return Number(rank); |
26 | 43 | } |
27 | 44 |
|
| 45 | + |
28 | 46 | // The line below allows us to load the getCardValue function into tests in other files. |
29 | 47 | // This will be useful in the "rewrite tests with jest" step. |
30 | 48 | module.exports = getCardValue; |
|
50 | 68 | } catch (e) {} |
51 | 69 |
|
52 | 70 | // What other invalid card cases can you think of? |
| 71 | +// Number cards |
| 72 | +assertEquals(getCardValue("2♠"), 2); |
| 73 | +assertEquals(getCardValue("10♥"), 10); |
| 74 | + |
| 75 | +// Face cards |
| 76 | +assertEquals(getCardValue("J♣"), 10); |
| 77 | +assertEquals(getCardValue("Q♦"), 10); |
| 78 | +assertEquals(getCardValue("K♠"), 10); |
| 79 | + |
| 80 | +// Ace |
| 81 | +assertEquals(getCardValue("A♥"), 11); |
| 82 | + |
| 83 | +// More invalid cases |
| 84 | +const invalidCards = ["", "A", "11♠", "1♠", "B♠", "10X", "♠A"]; |
| 85 | + |
| 86 | +for (const bad of invalidCards) { |
| 87 | + try { |
| 88 | + getCardValue(bad); |
| 89 | + console.error("Error was not thrown for invalid card:", bad); |
| 90 | + } catch (e) {} |
| 91 | +} |
0 commit comments