Skip to content

Instantly share code, notes, and snippets.

@javascripto
Created May 12, 2020 16:03
Show Gist options
  • Select an option

  • Save javascripto/423baf33a29a69188f7799b1f9da0188 to your computer and use it in GitHub Desktop.

Select an option

Save javascripto/423baf33a29a69188f7799b1f9da0188 to your computer and use it in GitHub Desktop.
class CPF {
static CPF_MASK = '$1.$2.$3-$4';
static CPF_REGEX = /(\d{3})(\d{3})(\d{3})(\d{2})/;
static generateFormated(): string {
return this.format(this.generate());
}
static format(cpf: string): string {
return cpf.replace(this.CPF_REGEX, this.CPF_MASK);
}
static removeFormatting(cpf: string): string {
return cpf.replace(/[-\.]/g, '');
}
static generate(): string {
const randomNumber = (Math.random() * 1_000_000_000).toString();
const integerString = parseInt(randomNumber).toString();
let _cpf = integerString.padStart(9, '0');
for (let digit = 0; digit < 100; digit++) {
const verifierDigit = digit.toString().padStart(2, '0');
if (this.isValid(_cpf + verifierDigit))
return _cpf += verifierDigit;
}
return _cpf;
}
static isValid(cpf: string): boolean {
const _cpf = this.removeFormatting(cpf);
let sum = 0, rest;
const ALL_DIGITS_ARE_THE_SAME = _cpf.split('')
.every(digit => digit === _cpf[0]);
if (ALL_DIGITS_ARE_THE_SAME)
return false;
for (let i = 1; i<= 9; i++)
sum += parseInt(_cpf.substring(i - 1, i)) * (11 - i);
rest = (sum * 10) % 11;
if ((rest === 10) || (rest === 11)) rest = 0;
if (rest !== parseInt(_cpf.substring(9, 10)))
return false;
sum = 0;
for (let j = 1; j <= 10; j++)
sum += parseInt(_cpf.substring(j - 1, j)) * (12 - j);
rest = (sum * 10) % 11;
if ((rest == 10) || (rest == 11)) rest = 0;
if (rest != parseInt(_cpf.substring(10, 11)))
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment