All files / isCNPJ index.ts

100% Statements 28/28
89.47% Branches 17/19
100% Functions 1/1
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x 11x   8x 11x   5x 5x 5x 5x 5x   11x   60x 60x 60x   5x   11x   11x   5x 5x 5x 5x 11x   65x 65x 65x   11x 11x   11x 11x  
export function isCNPJ(cnpj: string | null | undefined): boolean {
  if (!(typeof cnpj === 'string' && cnpj)) return false
 
  cnpj = cnpj.replace(/[\\.\\/-]/g, '')
  if (cnpj.length !== 14 || /^(\d)\1{13}$/.test(cnpj)) return false
 
  let length = cnpj.length - 2,
    numbers = cnpj.substring(0, length),
    digits = cnpj.substring(length),
    sum = 0,
    pos = length - 7
 
  for (let i = length; i >= 1; i--) {
    // @ts-ignore
    sum += numbers[length - i] * pos--
    if (pos < 2) pos = 9
  }
 
  console.log('Soma:', sum, 'Resto:', sum % 11) // <-- ADICIONE ESTA LINHA
 
  let result = sum % 11 < 2 ? 0 : 11 - (sum % 11)
 
  if (result !== parseInt(digits[0])) return false
 
  length++
  numbers = cnpj.substring(0, length)
  sum = 0
  pos = length - 7
  for (let i = length; i >= 1; i--) {
    // @ts-ignore
    sum += numbers[length - i] * pos--
    if (pos < 2) pos = 9
  }
 
  result = sum % 11 < 2 ? 0 : 11 - (sum % 11)
  console.log('Resultado esperado do segundo dígito:', result) // <-- ADICIONE ESTA LINHA
 
  return result === parseInt(digits[1])
}