Skip to content

Instantly share code, notes, and snippets.

@nwrox
Created April 13, 2019 02:44
Show Gist options
  • Save nwrox/07adbde5542bbe5e18f9b98e8389cd54 to your computer and use it in GitHub Desktop.
Save nwrox/07adbde5542bbe5e18f9b98e8389cd54 to your computer and use it in GitHub Desktop.
const m1 = Array.from({ length: 11 }, (k, v) => v)
.reverse()
.slice(0, 9)
const m2 = Array.from({ length: 12 }, (k, v) => v)
.reverse()
.slice(0, 10)
let tempCpf;
let digito;
let soma;
let resto;
cpf = cpf.trim();
cpf = cpf.replace(".", "").replace("-", "");
if (cpf.length != 11 || /([0]{11})|([1]{11})|([2]{11})|([3]{11})|([4]{11})|([5]{11})|([6]{11})|([7]{11})|([8]{11})|([9]{11})/.test(cpf))
console.log({ 1: false });
tempCpf = cpf.substring(0, 9);
soma = 0;
for(let i=0; i<9; i++)
soma += parseInt(tempCpf[i].toString()) * m1[i];
resto = soma % 11
resto = resto >= 2
? 11 - resto
: 0
digito = resto.toString();
tempCpf = tempCpf + digito;
soma = 0;
for(let i=0; i<10; i++)
soma += parseInt(tempCpf[i].toString()) * m2[i];
resto = soma % 11
resto = resto >= 2
? 11 - resto
: 0
digito = digito + resto.toString()
console.log({ 2: cpf.endsWith(digito) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment