Skip to content

Commit 7da75fd

Browse files
committed
card-validator.md.js updated
1 parent bc06097 commit 7da75fd

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Validates a credit card number based on specific rules:
3+
* - Must be 16 digits
4+
* - Must have at least two different digits
5+
* - Final digit must be even
6+
* - Sum of all digits must be greater than 16
7+
*
8+
* @param {string} cardNumber - The credit card number to validate
9+
* @returns {boolean} - true if valid, false if invalid
10+
*/
11+
function validateCreditCard(cardNumber) {
12+
// Rule 1: Check if length is exactly 16 digits and all are numbers
13+
if (!/^\d{16}$/.test(cardNumber)) {
14+
return false;
15+
}
16+
17+
// Convert string to array of numbers
18+
const digits = cardNumber.split('').map(Number);
19+
20+
// Rule 2: Check for at least two different digits
21+
const uniqueDigits = new Set(digits);
22+
if (uniqueDigits.size < 2) {
23+
return false;
24+
}
25+
26+
// Rule 3: Check if the final digit is even
27+
if (digits[digits.length - 1] % 2 !== 0) {
28+
return false;
29+
}
30+
31+
// Rule 4: Check if sum of all digits is greater than 16
32+
const sum = digits.reduce((acc, val) => acc + val, 0);
33+
if (sum <= 16) {
34+
return false;
35+
}
36+
37+
// All rules passed
38+
return true;
39+
}
40+
41+
// Example usage:
42+
console.log(validateCreditCard("9999777788880000")); // true
43+
console.log(validateCreditCard("6666666666661666")); // true
44+
console.log(validateCreditCard("a92332119c011112")); // false
45+
console.log(validateCreditCard("4444444444444444")); // false
46+
console.log(validateCreditCard("1111111111111110")); // false
47+
console.log(validateCreditCard("6666666666666661")); // false
48+
49+
module.exports = validateCreditCard;
50+
51+
const validateCreditCard = require('./credit-card-validator');
52+
53+
test("valid credit card number", () => {
54+
expect(validateCreditCard("9999777788880000")).toBe(true);
55+
});
56+
57+
test("invalid credit card number (all same digits)", () => {
58+
expect(validateCreditCard("4444444444444444")).toBe(false);
59+
});

0 commit comments

Comments
 (0)