Skip to content

Commit 478afbb

Browse files
committed
implement getCardValue
1 parent a0a794f commit 478afbb

1 file changed

Lines changed: 28 additions & 25 deletions

File tree

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,31 @@
1-
// This problem involves playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck
2-
3-
// Don't forget to write tests in implement-tests-with-node-test.
4-
5-
// Implement a function getCardValue, when given a string representing a playing card,
6-
// should return the numerical value of the card.
7-
8-
// A valid card string will contain a rank followed by the suit.
9-
// The rank can be one of the following strings:
10-
// "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
11-
// The suit can be one of the following emojis:
12-
// "♠", "♥", "♦", "♣"
13-
// For example: "A♠", "2♥", "10♥", "J♣", "Q♦", "K♦".
14-
15-
// When the card is an ace ("A"), the function should return 11.
16-
// When the card is a face card ("J", "Q", "K"), the function should return 10.
17-
// When the card is a number card ("2" to "10"), the function should return its numeric value.
18-
19-
// When the card string is invalid (not following the above format), the function should
20-
// throw an error.
1+
export function getCardValue(card) {
2+
const suit = card.slice(-1);
3+
const rank = card.slice(0, -1);
4+
const validSuits = "♠♥♦♣";
5+
const validRanks = [
6+
"A",
7+
"2",
8+
"3",
9+
"4",
10+
"5",
11+
"6",
12+
"7",
13+
"8",
14+
"9",
15+
"10",
16+
"J",
17+
"Q",
18+
"K",
19+
];
2120

22-
// Acceptance criteria:
23-
// After you have implemented the function, write tests to cover all the cases, and
24-
// execute the code to ensure all tests pass.
21+
if (!validSuits.includes(suit)) {
22+
throw new Error(`Expected a number followed by a suit, but got "${card}"`);
23+
}
24+
if (!validRanks.includes(rank)) {
25+
throw new Error(`Expected a number followed by a suit, but got "${card}"`);
26+
}
2527

26-
export function getCardValue(card) {
27-
// TODO: Implement this function
28+
if (rank === "A") return 11;
29+
if (rank === "J" || rank === "Q" || rank === "K") return 10;
30+
return Number(rank);
2831
}

0 commit comments

Comments
 (0)