Skip to content

Commit 267e816

Browse files
committed
fixed not throwing error issue
1 parent 2a9ffe9 commit 267e816

1 file changed

Lines changed: 23 additions & 17 deletions

File tree

Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,12 @@
2323

2424
function getCardValue(card) {
2525
// Handling invalid cards
26-
try {
27-
const rank = card.slice(0, -1); //rank of the card is everything except the last character of card string
28-
const suit = card.slice(-1); // suit is the last character of the card string
29-
if (!isValidCard(rank, suit)) {
30-
throw new Error("Invalid card");
31-
}
32-
if (rank === "J" || rank === "Q" || rank == "K") return 10;
33-
else if (rank == "A") return 11;
34-
else return Number(rank);
35-
} catch (e) {
36-
return e.message;
37-
}
26+
const rank = card.slice(0, -1); //rank of the card is everything except the last character of card string
27+
const suit = card.slice(-1); // suit is the last character of the card string
28+
if (!isValidCard(rank, suit)) throw new Error("Invalid card");
29+
if (rank === "J" || rank === "Q" || rank == "K") return 10;
30+
else if (rank == "A") return 11;
31+
else return Number(rank);
3832
}
3933

4034
function isValidCard(rank, suit) {
@@ -70,6 +64,15 @@ function assertEquals(actualOutput, targetOutput) {
7064
);
7165
}
7266

67+
function assertThrows(fnGetCardValue) {
68+
try {
69+
fnGetCardValue(); // run the function
70+
console.assert(false, "Expected function to throw an error");
71+
} catch (err) {
72+
console.assert(err instanceof Error, "Expected an Error to be thrown");
73+
}
74+
}
75+
7376
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
7477
// Examples:
7578
assertEquals(getCardValue("9♠"), 9);
@@ -79,8 +82,11 @@ assertEquals(getCardValue("A♣"), 11);
7982
assertEquals(getCardValue("2♠"), 2);
8083
assertEquals(getCardValue("J♦"), 10);
8184
assertEquals(getCardValue("K♠"), 10);
82-
assertEquals(getCardValue("Invalid"), "Invalid card");
83-
assertEquals(getCardValue("1Q"), "Invalid card");
84-
assertEquals(getCardValue("-10♦"), "Invalid card");
85-
assertEquals(getCardValue("♦K"), "Invalid card");
86-
assertEquals(getCardValue("Q♦♦"), "Invalid card");
85+
86+
// using function wrapper in the below lines of code so instead of passing teh result of function I can pass the function here,
87+
// and it is being called in try block of assertThrows function
88+
assertThrows(() => getCardValue("Invalid"));
89+
assertThrows(() => getCardValue("1Q"));
90+
assertThrows(() => getCardValue("-10♦"));
91+
assertThrows(() => getCardValue("♦K"));
92+
assertThrows(() => getCardValue("Q♦♦"));

0 commit comments

Comments
 (0)