generateCnpj function exported ✓ 100.0%
Last updated: 2026-02-24T21:07:57.500Z
Location
Metrics
LOC: 22
Complexity: 2
Params: 1
Coverage: 100.0% (8/8 lines, 55x executed)
Signature
generateCnpj(formatted = true): : string
Summary
Generates a valid Brazilian CNPJ (Cadastro Nacional de Pessoa Jurídica) with correct check digits.
Tags
#@param formatted - Whether to format as `XX.XXX.XXX/XXXX-XX` (default: `true`)#@returns A valid CNPJ string
Source Code
export function generateCnpj(formatted = true): string {
// First 8 digits are random, then 0001 (branch), then 2 check digits
const base = [...randomDigits(8), 0, 0, 0, 1];
const firstCheckDigit = calculateCnpjCheckDigit(
base,
[5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
);
base.push(firstCheckDigit);
const secondCheckDigit = calculateCnpjCheckDigit(
base,
[6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
);
base.push(secondCheckDigit);
const cnpj = base.join("");
if (!formatted) return cnpj;
return `${cnpj.slice(0, 2)}.${cnpj.slice(2, 5)}.${cnpj.slice(5, 8)}/${cnpj.slice(8, 12)}-${cnpj.slice(12)}`;
}
Dependencies (Outgoing)
| Target | Type |
|---|---|
| randomDigits | calls |
| calculateCnpjCheckDigit | calls |
Impact (Incoming)
| Source | Type |
|---|---|
| GeneratorFn | calls |
| generatePassword | uses |
| generateCpfCnpj | calls |