Skip to content

Commit 4eb2d5b

Browse files
committed
created tests and function for credit card validation
1 parent bfae2f8 commit 4eb2d5b

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

Sprint-3/3-stretch/creditCard-validator.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,33 @@ function creditCardValidator(cardNumber) {
55
//check if the length of the sanitized input is 16
66
if (sanitized.length !== 16) {
77
return false;
8-
} else {
9-
return true;
108
}
9+
// check if the sanitized input contains only digits
10+
if (!/^\d{16}$/.test(sanitized)) {
11+
return false;
12+
}
13+
14+
// check if there ara at least two different digits
15+
const uniqueDigits = new Set(sanitized);
16+
if (uniqueDigits.size < 2) {
17+
return false;
18+
}
19+
20+
// check if the last digit is even
21+
const lastDigit = Number(sanitized[sanitized.length - 1]);
22+
if (lastDigit % 2 !== 0) {
23+
return false;
24+
}
25+
26+
// check if the sum of all digits is greater than 16
27+
const sum = sanitized
28+
.split("")
29+
.reduce((total, digit) => total + Number(digit), 0);
30+
if (sum <= 16) {
31+
return false;
32+
}
33+
34+
return true;
1135
}
1236

1337
module.exports = creditCardValidator;

Sprint-3/3-stretch/creditCard-validator.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,25 @@ describe("creditCardValidator", () => {
55
expect(creditCardValidator("1234-5678-9012-3456")).toBe(true);
66
expect(creditCardValidator("1234 5678 9012 3456")).toBe(true);
77
});
8+
9+
test("should return false if the card number is not digit only", () => {
10+
expect(creditCardValidator("1234-5678-9012-345a")).toBe(false);
11+
expect(creditCardValidator("1234 5678 9012 3456")).toBe(true);
12+
});
13+
14+
test("should return false if the card number does not contain at least two different digits", () => {
15+
expect(creditCardValidator("1111-1111-1111-1111")).toBe(false);
16+
expect(creditCardValidator("1111 2222 2222 2222")).toBe(true);
17+
});
18+
19+
test("should return false if the card number does not end with an even digit", () => {
20+
expect(creditCardValidator("1234-5678-9012-3457")).toBe(false);
21+
expect(creditCardValidator("1234 5678 9012 3456")).toBe(true);
22+
});
23+
24+
test("should return false if the sum of all the digits is not greater than 16", () => {
25+
expect(creditCardValidator("0000-0000-0000-0000")).toBe(false);
26+
expect(creditCardValidator("1111 1111 1111 1111")).toBe(false);
27+
expect(creditCardValidator("1234 5678 9012 3456")).toBe(true);
28+
});
829
});

0 commit comments

Comments
 (0)