Skip to content

Commit 30ac3b1

Browse files
author
Baba05206
committed
Refactor getCardValue function to enhance handling of card ranks and improve error validation
1 parent e0d6ada commit 30ac3b1

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

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

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,28 @@
88
// write one test at a time, and make it pass, build your solution up methodically
99
// just make one change at a time -- don't rush -- programmers are deep and careful thinkers
1010
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
1212

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;
2416
}
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+
}
2633

2734
// The line below allows us to load the getCardValue function into tests in other files.
2835
// This will be useful in the "rewrite tests with jest" step.

0 commit comments

Comments
 (0)