Skip to content

Instantly share code, notes, and snippets.

@CesarBalzer
Last active February 7, 2024 19:28
Show Gist options
  • Save CesarBalzer/d1bcf63f19b748f86e199273a0d4c3c9 to your computer and use it in GitHub Desktop.
Save CesarBalzer/d1bcf63f19b748f86e199273a0d4c3c9 to your computer and use it in GitHub Desktop.
POSTMAN - Generate CPF/CNPJ valids, optional format
pm.globals.set("generateCpfCnpjFunction", `
function generateCpfCnpj(isCpf, format) {
//--CPF
function calculateVerificationDigit(part1, part2, part3, firstVerificationDigit) {
const numbers = \`\${part1}\${part2}\${part3}\`.split("");
if (firstVerificationDigit !== undefined) {
numbers[9] = firstVerificationDigit;
}
let sum = 0;
let index = 0;
let start = firstVerificationDigit !== undefined ? 11 : 10;
for (let number = start; number >= 2; number--) {
sum += parseInt(numbers[index]) * number;
index++;
}
const remainder = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
function generateRandomNumber() {
return Math.floor(Math.random() * 999).toString().padStart(3, '0');
}
function generateRandomCpf() {
const part1 = generateRandomNumber();
const part2 = generateRandomNumber();
const part3 = generateRandomNumber();
const verifier1 = calculateVerificationDigit(part1, part2, part3);
const verifier2 = calculateVerificationDigit(part1, part2, part3, verifier1);
return format
? \`\${part1}.\${part2}.\${part3}-\${verifier1}\${verifier2}\`
: \`\${part1}\${part2}\${part3}\${verifier1}\${verifier2}\`;
}
//--CNPJ
function randomDigit() {
return Math.floor(Math.random() * 10);
}
function generateCNPJBase() {
const cnpjBase = [];
for (let i = 0; i < 12; i++) {
cnpjBase.push(randomDigit());
}
return cnpjBase;
}
function calculateFirstVerifier(cnpjBase) {
const weight = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum = 0;
for (let i = 0; i < 12; i++) {
sum += cnpjBase[i] * weight[i];
}
const remainder = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
function calculateSecondVerifier(cnpjBase, firstVerifier) {
const weight = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum = 0;
for (let i = 0; i < 12; i++) {
sum += cnpjBase[i] * weight[i];
}
sum += firstVerifier * weight[12];
const remainder = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
function generateRandomCnpj() {
const cnpjBase = generateCNPJBase();
const firstVerifier = calculateFirstVerifier(cnpjBase);
const secondVerifier = calculateSecondVerifier(cnpjBase.concat(firstVerifier), firstVerifier);
const formattedCnpj = \`\${ cnpjBase.join('') }\${ firstVerifier }\${ secondVerifier }\`;
return format ? formattedCnpj.slice(0, 2) + '.' + formattedCnpj.slice(2, 5) + '.' + formattedCnpj.slice(5, 8) + '/' + formattedCnpj.slice(8, 12) + '-' + formattedCnpj.slice(12) : formattedCnpj;
}
if(isCpf){
return generateRandomCpf();
}else{
return generateRandomCnpj();
}
}
`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment