|
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 | | - const rank = card.slice(0, -1).toUpperCase(); // extract the rank by removing the last character (suit) |
| 11 | + const rank = card.slice(0, -1).toUpperCase(); // Extract rank by removing suit |
12 | 12 |
|
13 | | - if (rank === "A") { // ace |
14 | | - return 11; // default value for ace |
15 | | - } else if (rank === "K" || rank === "Q" || rank === "J" || rank === "10") { // face cards and 10 |
16 | | - return 10; // value for face cards and 10 |
17 | | - } else { |
18 | | - const numericRank = parseInt(rank, 10); // convert rank to a number |
19 | | - if (!isNaN(numericRank) && numericRank >= 2 && numericRank <= 9) { // check if it's a valid number card |
20 | | - return numericRank; // return the numeric value |
21 | | - } else { |
22 | | - throw new Error(`Invalid or unrecognized card rank: "${rank}"`); // handle invalid card ranks |
23 | | - } |
| 13 | + // Handle Ace |
| 14 | + if (rank === "A") { |
| 15 | + return 11; |
24 | 16 | } |
25 | | -} |
| 17 | + |
| 18 | + // Handle Face Cards and 10 |
| 19 | + const faceRanks = ["K", "Q", "J", "10"]; |
| 20 | + if (faceRanks.includes(rank)) { |
| 21 | + return 10; |
| 22 | + } |
| 23 | + |
| 24 | + // Handle Number Cards (2–9) with strict validation |
| 25 | + const numberRanks = ["2", "3", "4", "5", "6", "7", "8", "9"]; |
| 26 | + if (numberRanks.includes(rank)) { |
| 27 | + return parseInt(rank, 10); |
| 28 | + } |
| 29 | + |
| 30 | + // Handle invalid ranks |
| 31 | + throw new Error(`Invalid or unrecognized card rank: "${rank}"`); |
| 32 | +} |
26 | 33 |
|
27 | 34 | // The line below allows us to load the getCardValue function into tests in other files. |
28 | 35 | // This will be useful in the "rewrite tests with jest" step. |
|
0 commit comments