Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(isCreditCard): create allCards dynamically and get rid of hard-to-maintain hardcoded version #2117

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/lib/isCreditCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ const cards = {
unionpay: /^(6[27][0-9]{14}|^(81[0-9]{14,17}))$/,
visa: /^(?:4[0-9]{12})(?:[0-9]{3,6})?$/,
};
/* eslint-disable max-len */
const allCards = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;
/* eslint-enable max-len */

const allCards = (() => {
const tmpCardsArray = [];
for (const cardProvider in cards) {
// istanbul ignore else
if (cards.hasOwnProperty(cardProvider)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this if-statement needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I originally did not have it in there either, but there is an linting rule that forced me to add it :-)
It otherwise threw me guard-for-in error
https://eslint.org/docs/latest/rules/guard-for-in

tmpCardsArray.push(cards[cardProvider]);
}
}
return tmpCardsArray;
})();

export default function isCreditCard(card, options = {}) {
assertString(card);
Expand All @@ -26,7 +34,7 @@ export default function isCreditCard(card, options = {}) {
} else if (provider && !(provider.toLowerCase() in cards)) {
/* specific provider not in the list */
throw new Error(`${provider} is not a valid credit card provider.`);
} else if (!(allCards.test(sanitized))) {
} else if (!allCards.some(cardProvider => cardProvider.test(sanitized))) {
// no specific provider
return false;
}
Expand Down