Last active
March 23, 2022 02:42
-
-
Save jeovazero/b38738edbb7ba7696be6590ccc82e43d 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
// https://www.inf.ufpr.br/nicolui/grad/Programas/Curiosidades/Gerador-CPF/Algoritmo-CNPJ.txt | |
function validateDigit(cnpjValues: number[], extraDigit?: number) { | |
const values = extraDigit != null ? [...cnpjValues, extraDigit] : cnpjValues | |
let size = values.length | |
let position = size - 7 | |
let sum = 0 | |
for (let i = 0; i < size; i++) { | |
sum += values[i] * position-- | |
if (position < 2) { | |
position = 9 | |
} | |
} | |
sum = sum % 11 | |
const calculatedDV = sum < 2 ? 0 : 11 - sum | |
return calculatedDV | |
} | |
const randomQuarter = () => | |
Math.trunc(Math.random() * 10000) | |
.toString() | |
.padStart(4, '0') | |
function generateCnpj(): string { | |
const cnpj = randomQuarter() + randomQuarter() + '0001' | |
const values = cnpj.split('').map(x => parseInt(x, 10)) | |
const firstDV = validateDigit(values) | |
const secondDV = validateDigit(values, firstDV) | |
return `${cnpj}${firstDV}${secondDV}` | |
} | |
const p = (raw: string) => { | |
const rawValues = raw.split('').map(x => parseInt(x,10)) | |
let f = validateDigit(rawValues) | |
console.log(f) | |
console.log(validateDigit(rawValues,f)) | |
} | |
// 18261995000100 | |
p('182619950001') | |
p('523906180001') | |
for(let i = 0; i < 10; i++) { | |
console.log(generateCnpj()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment