Skip to content

Instantly share code, notes, and snippets.

@joel29dec
Created June 29, 2019 22:37
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 joel29dec/4e95cefe8dfeb112ff64900f76e5bd3d to your computer and use it in GitHub Desktop.
Save joel29dec/4e95cefe8dfeb112ff64900f76e5bd3d to your computer and use it in GitHub Desktop.
credit card validator
function validator(cardNumber){
const cardArray = cardNumber.toString().split("").map((e) => parseInt(e) )
validlen(cardArray);
const splitArr = arrSplit(cardArray)
const checksum = sumArrDigits(splitArr.arr1).reduce((a, c) => a + c) + splitArr.arr2.reduce((a, c) => a + c);
if (checksum % 10 == 0){
const typeValidatorArr = cardArray.slice(0,2)
const typeValidatorInt = parseInt(typeValidatorArr.join(""))
if (typeValidatorArr[0] == 4){
return "VISA"
}else if(typeValidatorInt == 34 || typeValidatorInt == 37){
return "AMERICAN EXPRESS";
}else if(typeValidatorInt == 22 || typeValidatorInt == 51 || typeValidatorInt == 52 || typeValidatorInt == 53 || typeValidatorInt == 54){
return "MASTERCARD";
}else if(typeValidatorInt == 35 ){
return "JCB";
}else if(typeValidatorInt == 60 ){
return "DISCOVER";
}else if(typeValidatorInt == 30 ){
return "DINERS CLUB";
}
}
}
console.log(validator(cardNumber));
function sumArrDigits(array){
return array.join("").split("").map(e => parseInt(e))
}
function validlen(arr){
// checks for card length of 13, 15, or 16
return arr.length == 13 || arr.length == 15 || arr.length == 16
}
function arrSplit(cardArray){
const selectOddValues = cardArray.filter((a,i)=>i%2 === 1);
const selectEvenValues = cardArray.filter((a,i)=>i%2 === 0);
let arr1;
let arr2;
if (cardArray.length % 2 == 1){
arr1 = selectOddValues.map(e => e * 2);
arr2 = selectEvenValues;
}else {
arr1 = selectEvenValues.map(e => e * 2);
arr2 = selectOddValues;
}
return {arr1, arr2}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment