Created
March 21, 2016 00:34
-
-
Save shgysk8zer0/271df4cfc9de41cc507a to your computer and use it in GitHub Desktop.
Validates a 16 digit credit card number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Validates a 16 digit credit card number | |
* | |
* @param string ccnum Any 16 digit number as a string | |
* @return boolean Whether or not it Validates | |
*/ | |
function checkCCNum(ccnum) { | |
if (ccnum.length !== 16 || ! /^\d+$/.test(ccnum)) { | |
return false; | |
} | |
let sums = ccnum.split('').map(num => parseInt(num)).reduce((nums, num, i) => { | |
if (i % 2 === 0) { | |
nums[0] += num; | |
if (num >= 5) { | |
nums[2]++; | |
} | |
} else { | |
nums[1] += num; | |
} | |
return nums; | |
}, [0, 0, 0]); | |
return (sums[0] * 2 + sums[1] + sums[2]) % 10 === 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment