Skip to content

Instantly share code, notes, and snippets.

@thyagodias
Last active March 3, 2020 18:39
Show Gist options
  • Save thyagodias/2676773fc841065d0d8c1c7aa35cb225 to your computer and use it in GitHub Desktop.
Save thyagodias/2676773fc841065d0d8c1c7aa35cb225 to your computer and use it in GitHub Desktop.
Validador de CPF
class ValidateCPF {
constructor (cpf) {
this.cpf = cpf.replace(/\D/g, '')
}
isValid () {
if (this.cpfWithRepeatedNumbers(this.cpf)) {
console.table({
valid: false,
cpf: this.cpf,
message: 'CPF contém números repetidos'
})
return
}
const firstPartOfCPF = this.cpf.substr(0, 9).split('')
const secondPartOfCPF = this.cpf.substr(0, 10).split('')
const firstCheckDigit = Number(this.cpf.charAt(9))
const secondCheckDigit = Number(this.cpf.charAt(10))
if (
firstCheckDigit == this.calculateDigit(firstPartOfCPF, 10) &&
secondCheckDigit == this.calculateDigit(secondPartOfCPF, 11)
) {
console.log('CPF é válido')
// Faça aqui a lógica para CPF válido
} else {
console.log('CPF é inválido')
// Faça aqui a lógica para CPF inválido
}
// implemente o retorno do método
}
cpfWithRepeatedNumbers (cpf) {
const invalidCpfs = [
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999'
]
return invalidCpfs.includes(cpf)
}
calculateTotal (multiplier) {
return function (acumulator, currentValue) {
return acumulator + currentValue * multiplier--
}
}
calculateDigit (firstPartOfCPF, multiplier) {
const total = firstPartOfCPF.reduce(this.calculateTotal(multiplier), 0)
const mod = total % 11
let digit = 11 - mod
if (mod > 9) {
digit = 0
}
return digit
}
}
module.exports = ValidateCPF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment