@@ -33,3 +33,64 @@ These are the requirements your project needs to fulfill:
3333- Return a boolean from the function to indicate whether the credit card number is valid.
3434
3535Good luck!
36+
37+ function validateCreditCard(number) {
38+ // Convert input to a string so we can check characters easily
39+ const numStr = String(number);
40+
41+ // Rule 1: Must be 16 digits, all numbers
42+ if (!/^\d{16}$/.test(numStr)) {
43+ return false;
44+ }
45+
46+ // Rule 2: Must contain at least two different digits
47+ const uniqueDigits = new Set(numStr);
48+ if (uniqueDigits.size < 2) {
49+ return false;
50+ }
51+
52+ // Rule 3: The last digit must be even
53+ const lastDigit = parseInt(numStr[ numStr.length - 1] );
54+ if (lastDigit % 2 !== 0) {
55+ return false;
56+ }
57+
58+ // Rule 4: The sum of all digits must be greater than 16
59+ const sum = numStr
60+ .split("")
61+ .map(Number)
62+ .reduce((a, b) => a + b, 0);
63+
64+ if (sum <= 16) {
65+ return false;
66+ }
67+
68+ // If all checks pass, return true ✅
69+ return true;
70+ }
71+
72+ module.exports = validateCreditCard;
73+
74+ const validateCreditCard = require("./validateCreditCard");
75+
76+ test("valid credit card numbers should return true", () => {
77+ expect(validateCreditCard("9999777788880000")).toBe(true);
78+ expect(validateCreditCard("6666666666661666")).toBe(true);
79+ });
80+
81+ test("invalid cards with letters should return false", () => {
82+ expect(validateCreditCard("a92332119c011112")).toBe(false);
83+ });
84+
85+ test("invalid cards with all same digits should return false", () => {
86+ expect(validateCreditCard("4444444444444444")).toBe(false);
87+ });
88+
89+ test("invalid cards with sum less than 16 should return false", () => {
90+ expect(validateCreditCard("1111111111111110")).toBe(false);
91+ });
92+
93+ test("invalid cards with odd final digit should return false", () => {
94+ expect(validateCreditCard("6666666666666661")).toBe(false);
95+ });
96+
0 commit comments