diff --git a/docs/index.md b/docs/index.md index a0d9309..993f842 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,7 +9,7 @@ hero: features: - title: Utils details: Métodos utilitários em TypeScript para facilitar tarefas comuns no front-end. - link: /utils/pluralize + link: /utils/index - title: Formatadores details: Métodos em TypeScript para formatar diversos tipos de dados. link: /formatters/index diff --git a/docs/utils/commaline.md b/docs/utils/commaline.md new file mode 100644 index 0000000..9c28b93 --- /dev/null +++ b/docs/utils/commaline.md @@ -0,0 +1,123 @@ +# Commaline + +Utilitário para formatar listas de strings com vírgulas e conjunção "e". + +## Instalação e Importação + +```typescript +import { commaline } from '@sysvale/foundry'; +``` + +## Função + +### `commaline()` + +Formata uma lista de strings adicionando vírgulas entre os itens e a conjunção "e" antes do último elemento. + +#### Sintaxes + +```typescript +// Assinatura 1: Usando string com índice e comprimento +commaline(str: string, index: number, length: number): string + +// Assinatura 2 (sobrecarga): Usando array de strings +commaline(arr: string[]): string +``` + +#### Parâmetros + +**Assinatura 1:** + +- **`str`** (`string`): A string atual sendo processada +- **`index`** (`number`): O índice da string atual na lista +- **`length`** (`number`): O comprimento total da lista + +**Assinatura 2 (sobrecarga):** + +- **`arr`** (`string[]`): Array de strings a ser formatado + +
+ +#### Retorno + +`string` - A string formatada com vírgulas e conjunção apropriadas + +#### Regras de Formatação + +1. **Um item**: Retorna o item sem nenhuma pontuação adicional +2. **Dois itens**: Retorna "item1 e item2" +3. **Três ou mais itens**: Retorna "item1, item2, item3 e item4" + - Vírgulas separam todos os itens exceto os dois últimos + - A conjunção "e" precede apenas o último item + +
+ +#### Exemplos + +**Usando array de strings:** + +```typescript +// Um item +commaline(['Abacate']); // → 'Abacate' + +// Dois itens +commaline(['manga', 'morango']); // → 'manga e morango' + +// Três itens +commaline(['manga', 'morango', 'uva']); // → 'manga, morango e uva' + +// Quatro ou mais itens +commaline(['manga', 'morango', 'uva', 'abacate']); // → 'manga, morango, uva e abacate' + +// Lista com muitos itens +commaline(['maçã', 'banana', 'laranja', 'pêra', 'kiwi', 'mamão']); +// → 'maçã, banana, laranja, pêra, kiwi e mamão' +``` + +
+ +**Usando string com índice (uso em v-for):** + +```typescript +// Primeiro item de uma lista de 4 +commaline('manga', 0, 4); // → 'manga, ' + +// Segundo item de uma lista de 4 +commaline('morango', 1, 4); // → 'morango, ' + +// Penúltimo item de uma lista de 4 +commaline('uva', 2, 4); // → 'uva e ' + +// Último item de uma lista de 4 +commaline('abacate', 3, 4); // → 'abacate' + +// Item único +commaline('Abacate', 0, 1); // → 'Abacate' +``` + +
+ +#### Tratamento de Erros + +A função lança um erro quando os parâmetros obrigatórios não são fornecidos: + +```typescript +// ❌ Erro: faltam parâmetros obrigatórios +commaline('Abacate'); +// → Error: 'Index and length must be provided when passing a string' + +// ✅ Correto +commaline(['Abacate']); // → 'Abacate' +``` + +## Notas + +- A função é **type-safe** com sobrecargas TypeScript +- **Imutável**: não modifica o array original +- **Compatível** com arrays vazios (retorna string vazia) + +## Limitações + +- Não suporta formatação de listas aninhadas +- A conjunção "e" é fixa (não permite personalização para "ou", "nem", etc.) +- Não oferece opções de localização para outros idiomas diff --git a/docs/utils/index.md b/docs/utils/index.md new file mode 100644 index 0000000..9ad31c6 --- /dev/null +++ b/docs/utils/index.md @@ -0,0 +1,17 @@ +# Funções utilitárias + +Este módulo fornece funções para formatar diversos tipos de dados. + +## Formatadores + +### pluralize() + +Funções para aplicação de plurais em palavras ou lista de palavras. + +- [Documentação](./pluralize.md) + +### commaline() + +Funções para formatar listas de strings com vírgulas e conjunção "e". + +- [Documentação](./commaline.md) diff --git a/eslint.config.cjs b/eslint.config.cjs index fda5455..f2d2f09 100644 --- a/eslint.config.cjs +++ b/eslint.config.cjs @@ -3,7 +3,6 @@ const typescript = require('@typescript-eslint/eslint-plugin'); const typescriptParser = require('@typescript-eslint/parser'); module.exports = [ - // Configuração global de ignores { ignores: [ '**/node_modules/**', @@ -57,8 +56,9 @@ module.exports = [ indent: ['error', 'tab'], quotes: ['error', 'single'], semi: ['error', 'always'], - - '@typescript-eslint/no-unused-vars': 'error', + 'no-redeclare': 'off', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-explicit-any': 'warn', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', diff --git a/package.json b/package.json index a94c6e3..69b1554 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sysvale/foundry", - "version": "1.1.0", + "version": "1.2.0", "description": "A forge for composables, helpers, and front-end utilities.", "type": "module", "main": "./dist/foundry.cjs.js", diff --git a/src/index.ts b/src/index.ts index 3cdaeab..1836e07 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ export * from './utils/pluralize'; +export * from './utils/commaline'; export { maskCpf, removeCpfMask } from './formatters/cpf'; export { maskPhone, removePhoneMask } from './formatters/phone'; diff --git a/src/utils/commaline.ts b/src/utils/commaline.ts new file mode 100644 index 0000000..6361b22 --- /dev/null +++ b/src/utils/commaline.ts @@ -0,0 +1,26 @@ +export function commaline(str: string, index: number, length: number): string; +export function commaline(arr: string[]): string; + +export function commaline( + strOrArray: string | string[], + index?: number, + length?: number +): string { + if (typeof strOrArray === 'string') { + if (typeof index === 'undefined' || typeof length === 'undefined') { + throw new Error( + 'Index and length must be provided when passing a string' + ); + } else { + if (index === length - 1) return strOrArray; + if (index === length - 2) return `${strOrArray} e `; + return `${strOrArray}, `; + } + } else { + if (!strOrArray.length || strOrArray[0] === '') return ''; + + return strOrArray.reduce((acc, cur, index, arr) => { + return (acc += commaline(cur, index, arr.length)); + }, ''); + } +} diff --git a/tests/commaline.test.ts b/tests/commaline.test.ts new file mode 100644 index 0000000..862dfc4 --- /dev/null +++ b/tests/commaline.test.ts @@ -0,0 +1,44 @@ +import { test, describe, expect } from 'vitest'; +import { commaline } from '../src/utils/commaline'; + +describe('commaline com strings', () => { + test('se as vírgulas não são colocadas quando há apenas um item na lista', () => { + expect(commaline('Abacate', 0, 1)).toBe('Abacate'); + }); + + test('se a conjunção "e" é utilizada quando há 2 ou mais items na lista', () => { + const list = ['manga', 'morango', 'uva', 'abacate']; + + const listWithCommas = list.reduce((acc, cur, index, arr) => { + return (acc += commaline(cur, index, arr.length)); + }, ''); + + expect(listWithCommas).toBe('manga, morango, uva e abacate'); + }); + + test('se um erro é emitido quando os parâmetros index e length não são enviados', () => { + expect(() => commaline('Abacate')).toThrow( + 'Index and length must be provided when passing a string' + ); + }); + + test('se é retornado string vazia quando uma string vazia é enviada', () => { + expect(commaline('', 0, 1)).toBe(''); + }); +}); + +describe('commaline com array de strings', () => { + test('se as vírgulas não são colocadas quando há apenas um item na lista', () => { + expect(commaline(['Abacate'])).toBe('Abacate'); + }); + + test('se a conjunção "e" é utilizada quando há 2 ou mais items na lista', () => { + expect(commaline(['manga', 'morango', 'uva', 'abacate'])).toBe( + 'manga, morango, uva e abacate' + ); + }); + + test('se é retornado string vazia quando uma string vazia é enviada', () => { + expect(commaline([''])).toBe(''); + }); +});