|
8 | 8 | // write one test at a time, and make it pass, build your solution up methodically |
9 | 9 | // just make one change at a time -- don't rush -- programmers are deep and careful thinkers |
10 | 10 | function getCardValue(card) { |
| 11 | + let rank = card.slice(0, -1); |
11 | 12 | if (rank === "A") { |
12 | 13 | return 11; |
13 | 14 | } |
| 15 | + if (rank >= "2" && rank <= "9") { |
| 16 | + return Number(rank); |
| 17 | + } |
| 18 | + if (rank === "J" || rank === "Q" || rank === "K") { |
| 19 | + return 10; |
| 20 | + } |
| 21 | + throw new Error("Invalid card rank"); |
14 | 22 | } |
15 | 23 |
|
16 | 24 | // The line below allows us to load the getCardValue function into tests in other files. |
@@ -39,19 +47,42 @@ assertEquals(aceofSpades, 11); |
39 | 47 | // When the function is called with such a card, |
40 | 48 | // Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5). |
41 | 49 | const fiveofHearts = getCardValue("5♥"); |
42 | | -// ====> write your test here, and then add a line to pass the test in the function above |
| 50 | +assertEquals(fiveofHearts, 5); |
43 | 51 |
|
44 | 52 | // Handle Face Cards (J, Q, K): |
45 | 53 | // Given a card with a rank of "10," "J," "Q," or "K", |
46 | 54 | // When the function is called with such a card, |
47 | 55 | // Then it should return the value 10, as these cards are worth 10 points each in blackjack. |
| 56 | +const ten = getCardValue("10"); |
| 57 | +assertEquals(ten, 10); |
| 58 | + |
| 59 | +const jack = getCardValue("J♦"); |
| 60 | +assertEquals(jack, 10); |
| 61 | + |
| 62 | +const queen = getCardValue("Q♠"); |
| 63 | +assertEquals(queen, 10); |
| 64 | + |
| 65 | +const king = getCardValue("K♥"); |
| 66 | +assertEquals(king, 10); |
48 | 67 |
|
49 | 68 | // Handle Ace (A): |
50 | 69 | // Given a card with a rank of "A", |
51 | 70 | // When the function is called with an Ace, |
52 | 71 | // Then it should, by default, assume the Ace is worth 11 points, which is a common rule in blackjack. |
53 | 72 |
|
| 73 | +const ace = getCardValue("A♥"); |
| 74 | +assertEquals(ace, 11); |
| 75 | + |
54 | 76 | // Handle Invalid Cards: |
55 | 77 | // Given a card with an invalid rank (neither a number nor a recognized face card), |
56 | 78 | // When the function is called with such a card, |
57 | 79 | // Then it should throw an error indicating "Invalid card rank." |
| 80 | + |
| 81 | +try { |
| 82 | + getCardValue("Z♥"); |
| 83 | +} catch (e) { |
| 84 | + console.assert( |
| 85 | + e.message === "Invalid card rank", |
| 86 | + `Expected "Invalid card rank" but got "${e.message}"` |
| 87 | + ); |
| 88 | +} |
0 commit comments