Skip to content

Commit f3b13d5

Browse files
committed
Create card validator with all 4 rules and tests
1 parent c37c56b commit f3b13d5

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Validates a credit card number string against the following rules:
2+
// - Must be exactly 16 digits (no letters or other characters)
3+
// - Must contain at least two different digits
4+
// - The final digit must be even
5+
// - The sum of all digits must be greater than 16
6+
7+
function isValidCardNumber(cardNumber) {
8+
// Rule 1: must be exactly 16 digit characters
9+
if (!/^\d{16}$/.test(cardNumber)) return false;
10+
11+
const digits = cardNumber.split("").map(Number);
12+
13+
// Rule 2: at least two different digits must be present
14+
if (new Set(digits).size < 2) return false;
15+
16+
// Rule 3: final digit must be even
17+
if (digits[15] % 2 !== 0) return false;
18+
19+
// Rule 4: sum of all digits must be greater than 16
20+
const sum = digits.reduce((acc, d) => acc + d, 0);
21+
if (sum <= 16) return false;
22+
23+
return true;
24+
}
25+
26+
module.exports = isValidCardNumber;
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const isValidCardNumber = require("./card-validator");
2+
3+
test("should return true for a valid card number", () => {
4+
expect(isValidCardNumber("9999777788880000")).toEqual(true);
5+
expect(isValidCardNumber("6666666666661666")).toEqual(true);
6+
});
7+
8+
test("should return false when card contains non-digit characters", () => {
9+
expect(isValidCardNumber("a92332119c011112")).toEqual(false);
10+
});
11+
12+
test("should return false when card has fewer than 16 digits", () => {
13+
expect(isValidCardNumber("123456789012345")).toEqual(false);
14+
});
15+
16+
test("should return false when card has more than 16 digits", () => {
17+
expect(isValidCardNumber("12345678901234567")).toEqual(false);
18+
});
19+
20+
test("should return false when all digits are the same", () => {
21+
expect(isValidCardNumber("4444444444444444")).toEqual(false);
22+
});
23+
24+
test("should return false when final digit is odd", () => {
25+
expect(isValidCardNumber("6666666666666661")).toEqual(false);
26+
});
27+
28+
test("should return false when sum of digits is not greater than 16", () => {
29+
expect(isValidCardNumber("1111111111111110")).toEqual(false);
30+
});

0 commit comments

Comments
 (0)