-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/formatters #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
068b886
Cria formatador de CPF
lucasn4s 835b40e
Cria validador de telefone
lucasn4s 5113363
Adiciona exportação de formatadores
lucasn4s b184573
Altera descrições de testes para português
lucasn4s fe6e19f
Adiciona documentação de formatadores de telefone
lucasn4s 1b97139
Adiciona documentação de formatador de CPF
lucasn4s 1058e6a
Adiciona seção de formatadores na documentação
lucasn4s ce3e90c
Atualiza versão do projeto
lucasn4s 13bbdcc
Adiciona trechos ignorados pelo prettier
lucasn4s ae245af
Adiciona exceções para o prettier
lucasn4s c5169e8
Ajusta exceções do prettier
lucasn4s 0bbb48b
Ajusta tipo de parâmetro do telefone
lucasn4s 6abd977
Remove caso de uso confuso
lucasn4s c63e2ae
Passa a considerar parâmetros que sejam número
lucasn4s 99abf70
Ajusta testes para aceitarem números
lucasn4s File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # Utilitários de Formatação de CPF | ||
|
|
||
| Este módulo fornece funções para aplicar e remover a máscara de CPF (Cadastro de Pessoas Físicas) em strings, facilitando a manipulação e exibição de documentos no padrão brasileiro. | ||
|
|
||
| ## Instalação e Importação | ||
|
|
||
| ```typescript | ||
| import { maskCpf, removeCpfMask } from '@sysvale/foundry'; | ||
| ``` | ||
|
|
||
| ## Funções | ||
|
|
||
| ### `maskCpf()` | ||
|
|
||
| Aplica a máscara de CPF no formato `XXX.XXX.XXX-XX` a uma string contendo apenas números. | ||
|
|
||
| #### Sintaxe | ||
|
|
||
| ```typescript | ||
| maskCpf(value: string): string | ||
| ``` | ||
|
|
||
| #### Parâmetros | ||
|
|
||
| - **`value`** (`string`): String contendo apenas números ou um CPF já formatado. | ||
|
|
||
| #### Retorno | ||
|
|
||
| `string` – O CPF formatado no padrão `XXX.XXX.XXX-XX` se a entrada tiver 11 dígitos. Caso contrário, retorna apenas os dígitos informados. | ||
|
|
||
| #### Exemplos | ||
|
|
||
| ```typescript | ||
| maskCpf('11111111111'); // → '111.111.111-11' | ||
| maskCpf(''); // → '' | ||
| maskCpf('1234567890'); // → '1234567890' (menos de 11 dígitos, retorna sem máscara) | ||
| ``` | ||
|
|
||
| #### Casos de Uso | ||
|
|
||
| - Exibir CPF formatado em formulários e relatórios. | ||
| - Garantir consistência visual de documentos em interfaces de usuário. | ||
|
|
||
| --- | ||
|
|
||
| ### `removeCpfMask()` | ||
|
|
||
| Remove qualquer máscara de CPF, retornando apenas os dígitos numéricos. | ||
|
|
||
| #### Sintaxe | ||
|
|
||
| ```typescript | ||
| removeCpfMask(value: string): string | ||
| ``` | ||
|
|
||
| #### Parâmetros | ||
|
|
||
| - **`value`** (`string`): String contendo um CPF formatado ou não. | ||
|
|
||
| #### Retorno | ||
|
|
||
| `string` – String contendo apenas os números do CPF. | ||
|
|
||
| #### Exemplos | ||
|
|
||
| ```typescript | ||
| removeCpfMask('111.111.111-11'); // → '11111111111' | ||
| removeCpfMask(''); // → '' | ||
| removeCpfMask('1234567890'); // → '1234567890' (não altera se não houver máscara) | ||
| ``` | ||
|
|
||
| #### Casos de Uso | ||
|
|
||
| - Armazenar CPFs em banco de dados sem formatação. | ||
| - Validar ou comparar CPFs independentemente do formato de entrada. | ||
|
|
||
| ## Casos de Uso Comuns | ||
|
|
||
| ### Formatação para exibição | ||
|
|
||
| ```typescript | ||
| const cpf = '12345678901'; | ||
| const formatted = maskCpf(cpf); // '123.456.789-01' | ||
| ``` | ||
|
|
||
| ### Remoção de máscara para validação | ||
|
|
||
| ```typescript | ||
| const masked = '123.456.789-01'; | ||
| const digits = removeCpfMask(masked); // '12345678901' | ||
| ``` | ||
|
|
||
| ## Limitações | ||
|
|
||
| - As funções não validam se o CPF é válido, apenas formatam ou removem a máscara. | ||
| - Se a string de entrada não tiver 11 dígitos, `maskCpf` retorna apenas os dígitos sem aplicar a máscara. | ||
| - Caracteres não numéricos são removidos por `removeCpfMask`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # Utilitários de Formatação | ||
|
|
||
| Este módulo fornece funções para formatar diversos tipos de dados. | ||
|
|
||
| ## Formatadores | ||
|
|
||
| ### CPF | ||
|
|
||
| Funções para aplicação ou remoção de máscaras em CPFs. | ||
|
|
||
| - [Documentação](./cpf.md) | ||
|
|
||
| ### Telefone | ||
|
|
||
| Funções para aplicação ou remoção de máscaras em números telefônicos brasileiros. | ||
|
|
||
| - [Documentação](./phone.md) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| # Utilitários de Formatação de Telefone | ||
|
|
||
| Este módulo fornece funções para aplicar e remover a máscara de números de telefone brasileiros, facilitando a manipulação e exibição de telefones fixos e celulares no padrão nacional. | ||
|
|
||
| ## Instalação e Importação | ||
|
|
||
| ```typescript | ||
| import { maskPhone, removePhoneMask } from '@sysvale/foundry'; | ||
| ``` | ||
|
|
||
| ## Funções | ||
|
|
||
| ### `maskPhone()` | ||
|
|
||
| Aplica a máscara de telefone brasileiro no formato `(XX) XXXXX-XXXX` para celulares (11 dígitos) ou `(XX) XXXX-XXXX` para fixos (10 dígitos). | ||
|
|
||
| #### Sintaxe | ||
|
|
||
| ```typescript | ||
| maskPhone(value: string): string | ||
| ``` | ||
|
|
||
| #### Parâmetros | ||
|
|
||
| - **`value`** (`string`): String contendo apenas números, telefone já formatado ou com caracteres especiais. | ||
|
|
||
| #### Retorno | ||
|
|
||
| `string` – O telefone formatado no padrão nacional, conforme a quantidade de dígitos. Se a entrada não tiver 10 ou 11 dígitos, retorna apenas os dígitos informados. | ||
|
|
||
| #### Exemplos | ||
|
|
||
| <!-- prettier-ignore --> | ||
| ```typescript | ||
| maskPhone('11987654321'); // → '(11) 98765-4321' | ||
| maskPhone('1187654321'); // → '(11) 8765-4321' | ||
| maskPhone(''); // → '' | ||
| maskPhone('123456789'); // → '123456789' (menos de 10 dígitos, retorna sem máscara) | ||
| maskPhone('(11) 98765-4321'); // → '(11) 98765-4321' (já formatado) | ||
| maskPhone('11.98765.4321'); // → '(11) 98765-4321' | ||
| maskPhone('11abc98765def4321');// → '(11) 98765-4321' | ||
| maskPhone('1'); // → '1' | ||
| ``` | ||
|
|
||
| #### Casos de Uso | ||
|
|
||
| - Exibir telefones formatados em formulários e relatórios. | ||
| - Garantir consistência visual de números de telefone em interfaces de usuário. | ||
|
|
||
| --- | ||
|
|
||
| ### `removePhoneMask()` | ||
|
|
||
| Remove qualquer máscara de telefone, retornando apenas os dígitos numéricos. | ||
|
|
||
| #### Sintaxe | ||
|
|
||
| ```typescript | ||
| removePhoneMask(value: string): string | ||
| ``` | ||
|
|
||
| #### Parâmetros | ||
|
|
||
| - **`value`** (`string`): String contendo um telefone formatado ou não. | ||
|
|
||
| #### Retorno | ||
|
|
||
| `string` – String contendo apenas os números do telefone. | ||
|
|
||
| #### Exemplos | ||
|
|
||
| <!-- prettier-ignore --> | ||
| ```typescript | ||
| removePhoneMask('(11) 98765-4321'); // → '11987654321' | ||
| removePhoneMask('(11) 8765-4321'); // → '1187654321' | ||
| removePhoneMask(''); // → '' | ||
| removePhoneMask('11987654321'); // → '11987654321' (sem máscara, retorna igual) | ||
| removePhoneMask('11 98765 4321'); // → '11987654321' | ||
| removePhoneMask('11.98765.4321'); // → '11.98765.4321' (pontos não são removidos) | ||
| removePhoneMask('11#98765#4321'); // → '11#98765#4321' (outros caracteres não são removidos) | ||
| removePhoneMask('(11) 98765-4321 ext.123'); // → '11987654321ext.123' | ||
| ``` | ||
|
|
||
| #### Casos de Uso | ||
|
|
||
| - Armazenar telefones em banco de dados sem formatação. | ||
| - Validar ou comparar telefones independentemente do formato de entrada. | ||
| - Remover apenas os caracteres de máscara padrão: parênteses, hífens e espaços. | ||
|
|
||
| ## Casos de Uso Comuns | ||
|
|
||
| ### Formatação para exibição | ||
|
|
||
| ```typescript | ||
| const phone = '11987654321'; | ||
| const formatted = maskPhone(phone); // '(11) 98765-4321' | ||
| ``` | ||
|
|
||
| ### Remoção de máscara para validação | ||
|
|
||
| ```typescript | ||
| const masked = '(11) 98765-4321'; | ||
| const digits = removePhoneMask(masked); // '11987654321' | ||
| ``` | ||
|
|
||
| ## Limitações | ||
|
|
||
| - As funções não validam se o número de telefone é válido, apenas formatam ou removem a máscara. | ||
| - Se a string de entrada não tiver 10 ou 11 dígitos, `maskPhone` retorna apenas os dígitos sem aplicar a máscara. | ||
| - `removePhoneMask` remove apenas parênteses, hífens e espaços; outros caracteres especiais permanecem. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| const maskCpf = (value: string | number) => { | ||
| let cpf = typeof value === 'number' ? value.toString() : value; | ||
|
|
||
| if (!cpf) { | ||
| return ''; | ||
| } | ||
|
|
||
| cpf = cpf.replace(/\D/g, ''); | ||
|
|
||
| if (cpf.length === 11) { | ||
| return `${cpf.substring(0, 3)}.${cpf.substring(3, 6)}.${cpf.substring(6, 9)}-${cpf.substring(9, 11)}`; | ||
| } | ||
|
|
||
| return cpf; | ||
| }; | ||
|
|
||
| const removeCpfMask = (value: string | number) => { | ||
| let cpf = typeof value === 'number' ? value.toString() : value; | ||
|
|
||
| if (!cpf) { | ||
| return ''; | ||
| } | ||
|
|
||
| return cpf.replace(/\D/g, ''); | ||
| }; | ||
|
|
||
| export { maskCpf, removeCpfMask }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| const maskPhone = (value: string | null | number | undefined) => { | ||
| let phone = typeof value === 'number' ? value.toString() : value; | ||
|
|
||
| if (!phone || phone.length === 0) { | ||
| return ''; | ||
| } | ||
|
|
||
| phone = phone.replace(/[^0-9]+/g, ''); | ||
|
|
||
| if (phone.length === 11) { | ||
| return `(${phone.substring(0, 2)}) ${phone.substring(2, 7)}-${phone.substring(7, 11)}`; | ||
| } | ||
|
|
||
| if (phone.length === 10) { | ||
| return `(${phone.substring(0, 2)}) ${phone.substring(2, 6)}-${phone.substring(6, 10)}`; | ||
| } | ||
| return phone; | ||
| }; | ||
|
|
||
| const removePhoneMask = (value: string | null | number | undefined) => { | ||
| let phone = typeof value === 'number' ? value.toString() : value; | ||
|
|
||
| if (!phone || phone.length === 0) { | ||
| return ''; | ||
| } | ||
|
|
||
| return phone.replace(/\(|\)|-|\s/g, ''); | ||
| }; | ||
|
|
||
| export { maskPhone, removePhoneMask }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| export * from './utils/pluralize'; | ||
| export { maskCpf, removeCpfMask } from './formatters/cpf'; | ||
| export { maskPhone, removePhoneMask } from './formatters/phone'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { describe, test, expect } from 'vitest'; | ||
| import { maskCpf, removeCpfMask } from '../src/formatters/cpf'; | ||
|
|
||
| describe('maskCpf', () => { | ||
| test('deve formatar cpf', () => { | ||
| expect(maskCpf('11111111111')).toBe('111.111.111-11'); | ||
| expect(maskCpf(11111111111)).toBe('111.111.111-11'); | ||
| }); | ||
|
|
||
| test('deve retornar string vazia quando cpf é vazio', () => { | ||
| expect(maskCpf('')).toBe(''); | ||
| }); | ||
|
|
||
| test('deve retornar valor como está quando cpf é inválido', () => { | ||
| expect(maskCpf('1234567890')).toBe('1234567890'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('removeCpfMask', () => { | ||
| test('deve remover máscara de cpf', () => { | ||
| expect(removeCpfMask('111.111.111-11')).toBe('11111111111'); | ||
| }); | ||
|
|
||
| test('deve retornar string vazia quando cpf é vazio', () => { | ||
| expect(removeCpfMask('')).toBe(''); | ||
| }); | ||
|
|
||
| test('deve retornar valor como está quando cpf é inválido', () => { | ||
| expect(removeCpfMask('1234567890')).toBe('1234567890'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.