Last active
July 6, 2020 18:15
-
-
Save funfunction/63773274cf4c88650ed259729a0c4515 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
@func | |
calculate if credit card number is valid | |
@param {number|string} ccn Credit Card Number | |
@return {boolean} | |
*/ | |
const isCcValidLuhn = ccn => { | |
const sum = ccn | |
.toString() | |
.trim() | |
.replace(/-/g, "") //removed dashes if exist | |
.split("") | |
.reverse() | |
.map(s => parseInt(s)) | |
.map((n, index) => { | |
if (index % 2 != 0) { | |
n = n * 2 >= 10 ? n * 2 - 9 : n * 2; | |
} | |
return n; | |
}) | |
.reduce((accu, curr) => accu + curr); | |
return sum % 10 == 0; | |
} | |
//@tests | |
const ccNumsTrue = ["4012-8888-8888-1881", "5105-1051-0510-5100", "3714-496353-98431", "4012888888881881"]; | |
const ccNumsFalse = ["1234-5678-9101-2131", "", "xyz"]; //throw on "" , , "xyz", 2e6 | |
logForeachParam(isCcValidLuhn)(ccNumsTrue); | |
logForeachParam(isCcValidLuhn)(ccNumsFalse); | |
// logForeachParam sourcecode at: https://gist.github.com/funfunction/42918a4751ae51828cfc4c2dd4c0678e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment