File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments