|
21 | 21 | // After you have implemented the function, write tests to cover all the cases, and |
22 | 22 | // execute the code to ensure all tests pass. |
23 | 23 |
|
| 24 | +function isSuit(suit) { |
| 25 | + if (suit === "♠" || suit === "♥" || suit === "♦" || suit === "♣") { |
| 26 | + return true; |
| 27 | + } |
| 28 | + return false; |
| 29 | +} |
| 30 | + |
24 | 31 | function getCardValue(card) { |
25 | | - const lastCharIndex = card.length - 1; |
26 | | - const rank = card.slice(0, lastCharIndex); |
27 | | - const suit = card.slice(lastCharIndex); |
| 32 | + // the length has to be 2 or 3 then we pass this check |
28 | 33 |
|
29 | | - if (rank === "10") { |
30 | | - return 10; |
| 34 | + if (typeof card !== "string") { |
| 35 | + throw new Error( |
| 36 | + `Expected type for ${card} is string, but got ${typeof card}` |
| 37 | + ); |
31 | 38 | } |
32 | 39 |
|
33 | | - if (card.length > 2) { |
34 | | - throw new Error("Invalid input length"); |
| 40 | + if (card.length !== 2 && card.length !== 3) { |
| 41 | + throw new Error(`Invalid input length for ${card}`); |
35 | 42 | } |
36 | 43 |
|
37 | | - if (!(suit === "♠" || suit === "♥" || suit === "♦" || suit === "♣")) { |
| 44 | + const lastCharIndex = card.length - 1; |
| 45 | + const rank = card.slice(0, lastCharIndex); |
| 46 | + const suit = card.slice(lastCharIndex); |
| 47 | + |
| 48 | + if (!isSuit(suit)) { |
38 | 49 | throw new Error( |
39 | | - "Invalid second character detected, only suits(♠♥♦♣) are allowed, but got this character:", |
40 | | - suit |
| 50 | + `Invalid last character detected, only suits(♠♥♦♣) are allowed, but got this character: ${suit}` |
41 | 51 | ); |
42 | 52 | } |
43 | 53 |
|
44 | | - if (rank == "A") { |
| 54 | + if (rank === "A") { |
45 | 55 | return 11; |
46 | | - } else if (rank == "J" || rank == "Q" || rank == "K") { |
| 56 | + } else if (rank === "J" || rank === "Q" || rank === "K") { |
47 | 57 | return 10; |
48 | | - } else if (!isNaN(rank)) { |
| 58 | + } else if (!isNaN(rank) && Number(rank) >= 2 && Number(rank) <= 10) { |
| 59 | + // check if number and within bounds |
49 | 60 | return Number(rank); |
50 | 61 | } else { |
51 | | - throw new Error("Invalid card"); |
| 62 | + throw new Error( |
| 63 | + `${card} was passed into the function which is invalid, because one of the conditions failed` |
| 64 | + ); |
52 | 65 | } |
53 | 66 | } |
54 | 67 |
|
|
0 commit comments