Skip to content

Commit 4002e46

Browse files
committed
Completed credit-card-validator exercise
1 parent aac72a4 commit 4002e46

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function creditCardValidator(cardNumber) {
2+
// Check that the card number contains numbers only
3+
if (isNaN(cardNumber)) return false;
4+
5+
// Convert the card number to a string so we can check its digits easily
6+
let cardNumberString = String(cardNumber);
7+
8+
// Check that the card number has exactly 16 digits
9+
if (cardNumberString.length != 16) return false;
10+
11+
// Check that the last digit is even
12+
if (cardNumberString[15] % 2 != 0) return false;
13+
14+
// Calculate the sum of all digits
15+
const sum = cardNumberString
16+
.split("")
17+
.reduce((sum, digit) => (sum += Number(digit)), 0);
18+
19+
// If the sum of all digits is 16 or less, the card is invalid
20+
if (sum <= 16) return false;
21+
22+
// Use Set to filter out duplicate digits
23+
let uniqueDigits = new Set(cardNumberString);
24+
25+
// Make sure the card number isn’t made up of all the same digit
26+
if (uniqueDigits.size < 2) return false;
27+
28+
// If all conditions pass, the card number is valid
29+
return true;
30+
}

0 commit comments

Comments
 (0)