-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcredit card validation system.js
71 lines (60 loc) · 2.39 KB
/
credit card validation system.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Here are the rules for a valid number:
Number must be 16 digits, all of them must be numbers
You must have at least two different digits represented (all of the digits cannot be the same)
The final digit must be even
The sum of all the digits must be greater than 16
*/
/*
******************* TODOs *******************
DONE: The credit card number must be 16 digits in length
DONE: All of the digits must be numbers
DONE: Turn the digit from a string to an integer (if the digit is in fact a digit and not another char)
DONE: The credit card number must be composed of at least two different digits (i.e. all of the digits cannot be the same)
DONE: The final digit of the credit card number must be even
DONE: The sum of all the digits must be greater than 16
*/
function validateCreditCard(credit_card_number){
// The credit card number must be 16 digits in length
if(credit_card_number.length !== 16){
return false;
}
// All of the digits must be numbers
for(var i = 0; i < credit_card_number.length; i++){
// store the current digit
var currentNumber = credit_card_number[i];
// turn the digit from a string to an integer (if the digit is in fact a digit and not another char)
currentNumber = Number.parseInt(currentNumber);
// check that the digit is a number
if(!Number.isInteger(currentNumber)){
return false;
}
}
// The credit card number must be composed of at least two different digits (i.e. all of the digits cannot be the same)
var obj = {};
for(var i = 0; i < credit_card_number.length; i++){
obj[credit_card_number[i]] = true;
}
if(Object.keys(obj).length < 2){
return false;
}
// The final digit of the credit card number must be even
if(credit_card_number[credit_card_number.length - 1] % 2 !== 0){
return false;
}
// The sum of all the digits must be greater than 16
var sum = 0;
for(var i = 0; i < credit_card_number.length; i++){
sum += Number(credit_card_number[i]);
}
if(sum <= 16){
return false;
}
return true;
};
/**** tests *****/
console.log(validateCreditCard('9999777788880000')); //true
console.log(validateCreditCard('6666666666661666')); //true
console.log(validateCreditCard('a92332119c011112')); //false
console.log(validateCreditCard('4444444444444444')); //false
console.log(validateCreditCard('1211111111111112')); //true