generateCnpj function exported ✓ 100.0%

Last updated: 2026-02-24T21:07:57.500Z

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)

graph LR generateCnpj["generateCnpj"] randomDigits["randomDigits"] calculateCnpjCheckDigit["calculateCnpjCheckDigit"] generateCnpj -->|calls| randomDigits generateCnpj -->|calls| calculateCnpjCheckDigit style generateCnpj fill:#dbeafe,stroke:#2563eb,stroke-width:2px click generateCnpj "77b61c5f0ba6b377.html" click randomDigits "2053b2f7a989c95f.html" click calculateCnpjCheckDigit "c26a9642e8863d68.html"
TargetType
randomDigits calls
calculateCnpjCheckDigit calls

Impact (Incoming)

graph LR generateCnpj["generateCnpj"] GeneratorFn["GeneratorFn"] generatePassword["generatePassword"] generateCpfCnpj["generateCpfCnpj"] GeneratorFn -->|calls| generateCnpj generatePassword -->|uses| generateCnpj generateCpfCnpj -->|calls| generateCnpj style generateCnpj fill:#dbeafe,stroke:#2563eb,stroke-width:2px click generateCnpj "77b61c5f0ba6b377.html" click GeneratorFn "07e2c388ba1ac3f3.html" click generatePassword "6edfc36473487c94.html" click generateCpfCnpj "5206cdac70a3cf88.html"
SourceType
GeneratorFn calls
generatePassword uses
generateCpfCnpj calls