Skip to content

Instantly share code, notes, and snippets.

@funfunction
Last active July 6, 2020 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funfunction/63773274cf4c88650ed259729a0c4515 to your computer and use it in GitHub Desktop.
Save funfunction/63773274cf4c88650ed259729a0c4515 to your computer and use it in GitHub Desktop.
/**
@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