Created
May 12, 2022 22:41
-
-
Save javascripto/e5c1abda7a32a2208cdbb9557348e62f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CPF { | |
| static CPF_MASK = '$1.$2.$3-$4'; | |
| static CPF_REGEX = /(\d{3})(\d{3})(\d{3})(\d{2})/; | |
| static generateFormated() { | |
| return this.format(this.generate()); | |
| } | |
| static format(cpf) { | |
| return cpf.replace(this.CPF_REGEX, this.CPF_MASK); | |
| } | |
| static removeFormatting(cpf) { | |
| return cpf.replace(/[-\.]/g, ''); | |
| } | |
| static generate() { | |
| const randomNumber = (Math.random() * 1000000000).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) { | |
| 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; | |
| } | |
| } | |
| console.log(CPF.generate()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment