ContaAzul / creditcard.js

A simple credit card validation library in JavaScript
http://contaazul.github.io/creditcard.js/
Other
374 stars 82 forks source link

Apply more functional concepts in this library #79

Closed carlosrberto closed 3 years ago

carlosrberto commented 6 years ago

As you suggest @fernahh I'm replicating my coments from https://github.com/ContaAzul/creditcard.js/pull/78 here.

I think https://github.com/ContaAzul/creditcard.js/pull/78 is a good start point for turning this library more functional.

As an improvement, but not really required I also suggest applying more funcional concepts like decomposing some functions in smaller ones with less responsibilities.

For example isSecurityCodeValid:

export function isSecurityCodeValid(number, code) {
  let brand = getCreditCardNameByNumber(number);
  let numberLength;

  numberLength = (brand === 'Amex') ? 4 : 3;
  let regex = new RegExp(`^[0-9]{${numberLength}}$`);

  return regex.test(code);
}

could be refactored to something like:


const isSecurityCodeValid = (number, code) =>
  isCodeLengthValid(code, getBrandCodeLength(getBrand(number)));

or using some simple functional helpers like compose and curry for better readability:

const isSecurityCodeValid = (number, code) =>
  compose(curry(isCodeLengthValid)(code), getBrandCodeLength, getBrand)(number);

Another example isExpirationDateValid:

export function isExpirationDateValid(paramMonth, paramYearn) {
  const month = parseInt(paramMonth, 10);
  const year = parseInt(paramYearn, 10);

  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;

  if (isNaN(month) || isNaN(year))
    return false;

  if (year === currentYear && month < currentMonth)
    return false;

  if (month < 1 || month > 12)
    return false;

  return !(year < 1000 || year >= 3000);
}

could be:

export const isExpirationDateValid = (month, year) => 
  isValidMonth(month) && isValidYear(year) && !isPastDate(new Date(year, month));
fernahh commented 6 years ago

@carlosrberto can you get this issue for V3?

carlosrberto commented 6 years ago

Yes, I can. I'll start working on this issue soon @fernahh!

dedicio commented 3 years ago

HI @carlosrberto

Thanks for your contribution!

That suggestions was implemented in PR #120

See more details: https://contaazul.github.io/creditcard.js/