Skip to content

Instantly share code, notes, and snippets.

@williamokano
Created March 30, 2017 18:50
Show Gist options
  • Save williamokano/e891de2285e9ce0a1c3589727d23e388 to your computer and use it in GitHub Desktop.
Save williamokano/e891de2285e9ce0a1c3589727d23e388 to your computer and use it in GitHub Desktop.
function geraCpf() {
const cpf = [
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9),
geraInt(0, 9)].join('');
const dv1 = calcDvMod11(cpf);
const dv2 = calcDvMod11(`${cpf}${dv1}`);
return `${cpf}${dv1}${dv2}`;
}
function geraInt(min, max) {
return Math.floor(Math.random() * max) + min;
}
function calcDvMod11(str) {
const tokens = str.split('');
const mod = 11;
let i = tokens.length + 1;
let sum = 0;
for (let token of tokens) {
sum += parseInt(token, 10) * i--;
}
const resto = sum % mod;
if (resto < 2) {
return 0;
}
return mod - resto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment