Skip to content

Commit

Permalink
feat: add prettier and revalidating functions with better tests
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel-logan committed Mar 17, 2024
1 parent 7f54b6d commit bc24ede
Show file tree
Hide file tree
Showing 39 changed files with 1,372 additions and 1,181 deletions.
54 changes: 46 additions & 8 deletions packages/typescript/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,49 @@
/* eslint-env node */
module.exports = {
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
root: true,
rules: {
semi: ['error', 'always'],
quotes: ['error', 'single'],
}
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/strict-type-checked',
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
project: true,
tsconfigRootDir: __dirname,
},
plugins: ['@typescript-eslint'],
root: true,
rules: {
'no-else-return': ['error', { allowElseIf: false }],
'consistent-return': 'error',
'no-console': ['warn', { allow: ['warn', 'error'] }], // Here you are allowing console.warn and console.error
'@typescript-eslint/typedef': [
'error',
{
variableDeclaration: true,
memberVariableDeclaration: true,
},
],
'@typescript-eslint/explicit-module-boundary-types': 'error',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'class',
format: ['PascalCase'],
},
],
'@typescript-eslint/prefer-readonly': 'error',
'@typescript-eslint/explicit-member-accessibility': [
'error',
{
accessibility: 'explicit',
overrides: {
accessors: 'explicit',
constructors: 'no-public',
methods: 'explicit',
properties: 'explicit',
parameterProperties: 'explicit',
},
},
],
},
};
3 changes: 3 additions & 0 deletions packages/typescript/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist
node_modules
coverage
6 changes: 6 additions & 0 deletions packages/typescript/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 100,
}
58 changes: 29 additions & 29 deletions packages/typescript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,34 @@ import { ValidateFunctions, IsValidFunctions } from './src/types';

export {
cpfIsValid,
cnpjIsValid,
isEmail,
validateEmail,
isCEP,
validateUsername,
validatePassword,
getOnlyEmail,
isCreditCardValid,
identifyFlagCard,
isMACAddress,
isAscii,
isBase64,
isDate,
isDecimal,
isEmpty,
isMD5,
isPort,
isPostalCode,
isTime,
validatePassportNumber,
validateBRPhoneNumber,
validateUSPhoneNumber,
validatePhoneNumber,
isNumber,
passwordStrengthTester,
validateName,
validateSurname,
validateTextarea,
cnpjIsValid,
isEmail,
validateEmail,
isCEP,
validateUsername,
validatePassword,
getOnlyEmail,
isCreditCardValid,
identifyFlagCard,
isMACAddress,
isAscii,
isBase64,
isDate,
isDecimal,
isEmpty,
isMD5,
isPort,
isPostalCode,
isTime,
validatePassportNumber,
validateBRPhoneNumber,
validateUSPhoneNumber,
validatePhoneNumber,
isNumber,
passwordStrengthTester,
validateName,
validateSurname,
validateTextarea,
ValidateFunctions,
IsValidFunctions
IsValidFunctions,
};
19 changes: 11 additions & 8 deletions packages/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
"types": "./types/index.d.ts",
"scripts": {
"test": "jest --coverage",
"test:file": "jest tests/src/validateEmail.test --watch",
"test:watch": "jest --watch",
"test:file": "jest tests/src/validateEmail.test --watch",
"test:watch": "jest --watch",
"build": "npx tsc",
"build:types": "tsc -p tsconfig.types.json"
"build:types": "tsc -p tsconfig.types.json"
},
"repository": {
"type": "git",
Expand Down Expand Up @@ -43,12 +43,15 @@
"@types/jest": "^29.5.12",
"@types/mocha": "^10.0.6",
"@types/node": "^20.5.1",
"@typescript-eslint/eslint-plugin": "^6.4.0",
"@typescript-eslint/parser": "^6.4.0",
"eslint": "^8.47.0",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"jest": "^29.6.4",
"prettier": "^3.2.5",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
"typescript": "^5.1.6"
"ts-node": "^10.9.2",
"typescript": "^5.4.2"
}
}
152 changes: 81 additions & 71 deletions packages/typescript/src/cnpjValidator.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
// Função para calcular o primeiro dígito verificador
function calculateFirstVerifier(cnpjBase: number[]): number {
const weight: Array<number> = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum: number = 0;
for (let i: number = 0; i < 12; i += 1) {
sum += cnpjBase[i] * weight[i];
}
const remainder: number = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
const weight: Array<number> = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum: number = 0;
for (let i: number = 0; i < 12; i += 1) {
sum += cnpjBase[i] * weight[i];
}
const remainder: number = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
// Função para calcular o segundo dígito verificador
function calculateSecondVerifier(cnpjBase: number[], firstVerifier: number): number {
const weight: number[] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum: number = 0;
for (let i: number = 0; i < 12; i += 1) {
sum += cnpjBase[i] * weight[i];
}
sum += firstVerifier * weight[12];
const remainder: number = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
const weight: number[] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
let sum: number = 0;
for (let i: number = 0; i < 12; i += 1) {
sum += cnpjBase[i] * weight[i];
}
sum += firstVerifier * weight[12];
const remainder: number = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}

const defaultErrorMsg: string[] = ['CNPJ invalid', 'CNPJ must have 14 numerical digits', 'CNPJ is not valid', 'Unknown error'];
const defaultErrorMsg: string[] = [
'CNPJ invalid',
'CNPJ must have 14 numerical digits',
'CNPJ is not valid',
'Unknown error',
];

/**
* @param cnpj
Expand All @@ -38,66 +43,71 @@ const defaultErrorMsg: string[] = ['CNPJ invalid', 'CNPJ must have 14 numerical
* @returns An object with 'isValid' (boolean) and 'errorMsg' (string) properties.
*/

function cnpjIsValid(cnpj: string, errorMsg: (string|null)[] = defaultErrorMsg): {
function cnpjIsValid(
cnpj: string,
errorMsg: (string | null)[] | null = defaultErrorMsg,
): {
isValid: boolean;
errorMsg: string | null;
} {
if (typeof cnpj !== 'string') throw new TypeError('The input should be a string.');
// Check para saber se as mensagens que sao passadas sao validas
// caso contrario retorna um ERRO
if (errorMsg) {
if (!Array.isArray(errorMsg)) throw new Error('Must be an Array');
for (let index: number = 0; index < errorMsg.length; index += 1) {
if (errorMsg[index] != null && typeof errorMsg[index] !== 'string') {
throw new TypeError('All values within the array must be strings or null/undefined.');
}
}
}

if (typeof cnpj !== 'string') throw new TypeError('The input should be a string.');
// Check para saber se as mensagens que sao passadas sao validas
// caso contrario retorna um ERRO
if (errorMsg) {
if (!Array.isArray(errorMsg)) throw new Error('Must be an Array');
for (let index: number = 0; index < errorMsg.length; index += 1) {
if (errorMsg[index] != null && typeof errorMsg[index] !== 'string') {
throw new TypeError('All values within the array must be strings or null/undefined.');
}
}
}

// Função interna para obter a mensagem de erro
function getErrorMessage(index: number): string {
const errorMessage: string|null = errorMsg[index];
// Função interna para obter a mensagem de erro
function getErrorMessage(index: number): string {
const errorMessage: string | null = errorMsg ? errorMsg[index] : null;
return errorMessage != null ? errorMessage : defaultErrorMsg[index];
}
}

try {
if (!cnpj) {
return {
isValid: false,
errorMsg: getErrorMessage(0), // 'CNPJ invalid'
};
}
// Check if the CNPJ has 14 digits
if (cnpj.length !== 14 && cnpj.length !== 18) {
return {
isValid: false,
errorMsg: getErrorMessage(1), // 'CNPJ must have 14 numerical digits'
};
}
// Remove any non-digit characters from the CNPJ string
const cnpjClean: string = cnpj.replace(/\D+/g, '');
// Convert the CNPJ string to an array of digits
const cnpjArray: number[] = cnpjClean.split('').map(Number);
// Calculate the first and second verifiers
const firstVerifier: number = calculateFirstVerifier(cnpjArray.slice(0, 12));
const secondVerifier: number = calculateSecondVerifier(cnpjArray.slice(0, 12).concat(firstVerifier), firstVerifier);
// Check if the calculated verifiers match the ones in the CNPJ
if (cnpjArray[12] === firstVerifier && cnpjArray[13] === secondVerifier) {
return {
isValid: true,
errorMsg: null,
};
}
return {
isValid: false,
errorMsg: getErrorMessage(2), // 'CNPJ is not valid'
};
} catch (error) {
return {
isValid: false,
errorMsg: getErrorMessage(3), // 'Unknown error'
};
}
try {
if (!cnpj) {
return {
isValid: false,
errorMsg: getErrorMessage(0), // 'CNPJ invalid'
};
}
// Check if the CNPJ has 14 digits
if (cnpj.length !== 14 && cnpj.length !== 18) {
return {
isValid: false,
errorMsg: getErrorMessage(1), // 'CNPJ must have 14 numerical digits'
};
}
// Remove any non-digit characters from the CNPJ string
const cnpjClean: string = cnpj.replace(/\D+/g, '');
// Convert the CNPJ string to an array of digits
const cnpjArray: number[] = cnpjClean.split('').map(Number);
// Calculate the first and second verifiers
const firstVerifier: number = calculateFirstVerifier(cnpjArray.slice(0, 12));
const secondVerifier: number = calculateSecondVerifier(
cnpjArray.slice(0, 12).concat(firstVerifier),
firstVerifier,
);
// Check if the calculated verifiers match the ones in the CNPJ
if (cnpjArray[12] === firstVerifier && cnpjArray[13] === secondVerifier) {
return {
isValid: true,
errorMsg: null,
};
}
return {
isValid: false,
errorMsg: getErrorMessage(2), // 'CNPJ is not valid'
};
} catch (error) {
return {
isValid: false,
errorMsg: getErrorMessage(3), // 'Unknown error'
};
}
}
export default cnpjIsValid;
Loading

0 comments on commit bc24ede

Please sign in to comment.