Skip to content

Commit 4f63a8d

Browse files
London | 26-ITP-May | Yonatan Teklemariam | Sprint 3 | Strech-credit-card-validator
1 parent b31a586 commit 4f63a8d

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
function validateCreditCard(cardNumber) {
2+
if (cardNumber.length !== 16) {
3+
return false; // this line of code checks whether the card number is 16 digits long or not
4+
}
5+
let index = 0;
6+
while (index < cardNumber.length) {
7+
if (cardNumber[index] < "0" || cardNumber[index] > "9") {
8+
return false; // this line of code checks whether the card number is composed of digits not other characters
9+
}
10+
index++;
11+
}
12+
const firstDigit = cardNumber[0]; // first digit of the card number is stored for the purpose of checking up whether two digits are identical or not
13+
14+
index = 1;
15+
while (index < cardNumber.length) {
16+
if (cardNumber[index] !== firstDigit) {
17+
break; // loop ends immediately here to give way to the next check
18+
}
19+
index++;
20+
}
21+
if (index === cardNumber.length) {
22+
return false;
23+
}
24+
const lastDigit = cardNumber.slice(-1);
25+
const lastNumber = Number(lastDigit);
26+
27+
if (lastNumber % 2 !== 0) {
28+
return false; // this line of code checks whether the last digit of the card number is divisible by 2 in other words "even" or not
29+
}
30+
31+
let total = 0;
32+
index = 0;
33+
while (index < cardNumber.length) {
34+
total += Number(cardNumber[index]);
35+
index++;
36+
}
37+
if (total <= 16) {
38+
return false; // this line of code checks whether the sum of all the digits in the card number is more than 16 or not
39+
}
40+
41+
return true;
42+
}
43+
console.log(validateCreditCard("9999777788880000"));

0 commit comments

Comments
 (0)