1matriz = matriz || {}; 2matriz.datatype = matriz.datatype || {} 3matriz.datatype.CNPJ = function (cnpj) { 4 5 // Converte para maiúsculas e remove caracteres não alfanuméricos 6 cnpj = cnpj.toUpperCase().replace(/[^A-Z0-9]+/g, ''); 7 8 validaTamanho(); 9 10 // Calcula os dÃgitos verificadores 11 const primeiroDV = calculaDV(cnpj.substring(0, 12)); 12 const segundoDV = calculaDV(cnpj.substring(0, 12) + primeiroDV); 13 const cnpjCorreto = cnpj.substring(0, 12) + primeiroDV + segundoDV; 14 15 // console.log(`DÃgitos verificadores calculados: ${primeiroDV}${segundoDV}`); 16 // console.log(`CNPJ correto: ${cnpjCorreto}`); 17 18 if (cnpj !== cnpjCorreto) { 19 // console.log('CNPJ inválido.'); 20 throw new Error('CNPJ inválido.'); 21 // return false; 22 } 23 24 // console.log('CNPJ válido.'); 25 return { 26 asString: function () { 27 return cnpj; 28 } 29 }; 30 31 // Valida se o CNPJ tem 14 caracteres 32 function validaTamanho() { 33 if (cnpj.length !== 14) { 34 throw new Error("CNPJ deve possuir 14 dÃgitos."); 35 } 36 } 37 38 // Converte caractere alfanumérico para valor numérico conforme tabela do SERPRO 39 function valorParaDV(char) { 40 const ascii = char.charCodeAt(0); 41 if ((ascii >= 48 && ascii <= 57) || (ascii >= 65 && ascii <= 90)) { 42 return ascii - 48; 43 } else { 44 throw new Error(`Caractere inválido para CNPJ: ${char}`); 45 } 46 } 47 48 // Calcula o dÃgito verificador com pesos de 2 a 9 aplicados da direita para a esquerda 49 function calculaDV(cnpjIncompleto) { 50 let soma = 0; 51 let peso = 2; 52 53 for (let i = cnpjIncompleto.length - 1; i >= 0; i--) { 54 const digitoAtual = cnpjIncompleto.charAt(i); 55 const valor = valorParaDV(digitoAtual); 56 soma += valor * peso; 57 58 peso++; 59 if (peso > 9) peso = 2; 60 } 61 62 const resto = soma % 11; 63 return resto < 2 ? '0' : (11 - resto).toString(); 64 } 65 }; 66 67 68 69
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.