Skip to content

Instantly share code, notes, and snippets.

@mohokh67
Last active April 29, 2020 10:56
Show Gist options
  • Save mohokh67/4a01dc85ae884e5b7e057672a789fa4a to your computer and use it in GitHub Desktop.
Save mohokh67/4a01dc85ae884e5b7e057672a789fa4a to your computer and use it in GitHub Desktop.
Credit card validation
const validCreditCard = (cardNumber) => {
const newInput = cardNumber.toString();
let first = 0;
let second = 0;
if (newInput.length !== 16) {
return false;
}
for (let i = 15; i >= 0; i--) {
if (i % 2 === 1) {
first += Number(newInput[i]);
} else {
const temp = Number(newInput[i]) * 2;
if (temp < 10) {
second += temp;
} else {
const newTemp = temp.toString();
const secondNumber = Number(newTemp[0]) + Number(newTemp[1]);
second += secondNumber;
}
}
}
if ((first + second) % 10 === 0) {
return true;
}
};
console.log(validCreditCard(4659420912881451));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment