Skip to content

Commit 48b1a54

Browse files
Implement card value function & tests
1 parent da74f22 commit 48b1a54

2 files changed

Lines changed: 55 additions & 4 deletions

File tree

‎implement-and-rewrite-tests/implement-tests-with-node-test/3-get-card-value.test.js‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,36 @@ import test from "node:test";
33

44
import { getCardValue } from "../implement/3-get-card-value.js";
55

6-
// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards.
6+
test("Ace returns 11", () => {
7+
assert.equal(getCardValue("A♠"), 11);
8+
});
9+
10+
test("Face cards returns 10", () => {
11+
assert.equal(getCardValue("J♣"), 10);
12+
assert.equal(getCardValue("Q♦"), 10);
13+
assert.equal(getCardValue("K♥"), 10);
14+
});
15+
16+
test("Number cards return their numerical value", () => {
17+
assert.equal(getCardValue("2♥"), 2);
18+
assert.equal(getCardValue("10♥"), 10);
19+
});
720

821
test("Valid single-digit card", () => {
922
assert.equal(getCardValue("9♠"), 9);
1023
});
1124

1225
test("Arbitrary non-card string", () => {
13-
assert.throws(() => getCardValue("invalid"), /Expected a number followed by a suit, but got "invalid"/, "Expected clear error");
26+
assert.throws(
27+
() => getCardValue("invalid"),
28+
/Expected a number followed by a suit, but got "invalid"/,
29+
"Expected clear error"
30+
);
1431
});
1532

16-
// TODO: What other invalid card cases can you think of?
33+
test("Invalid suit throws an error", () => {
34+
assert.throws(
35+
() => getCardValue("9X"),
36+
/Expected a number followed by a suit, but got "9X"/
37+
);
38+
});

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,34 @@
2424
// execute the code to ensure all tests pass.
2525

2626
export function getCardValue(card) {
27-
// TODO: Implement this function
27+
const rank = card.slice(0, -1);
28+
const suit = card.slice(-1);
29+
30+
const validRanks = [
31+
"A",
32+
"2",
33+
"3",
34+
"4",
35+
"5",
36+
"6",
37+
"7",
38+
"8",
39+
"9",
40+
"10",
41+
"J",
42+
"Q",
43+
"K",
44+
];
45+
const validSuits = ["♠", "♥", "♦", "♣"];
46+
47+
if (!validRanks.includes(rank) || !validSuits.includes(suit)) {
48+
throw new Error(`Expected a number followed by a suit, but got "${card}"`);
49+
}
50+
if (rank === "A") {
51+
return 11;
52+
} else if (rank === "J" || rank === "Q" || rank === "K") {
53+
return 10;
54+
} else {
55+
return Number(rank);
56+
}
2857
}

0 commit comments

Comments
 (0)