Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
123 changes: 123 additions & 0 deletions docs/utils/commaline.md
Original file line number Diff line number Diff line change
@@ -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

<br />

#### 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

<br />

#### 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'
```

<br />

**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'
```

<br />

#### 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
17 changes: 17 additions & 0 deletions docs/utils/index.md
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 3 additions & 3 deletions eslint.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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/**',
Expand Down Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './utils/pluralize';
export * from './utils/commaline';
export { maskCpf, removeCpfMask } from './formatters/cpf';
export { maskPhone, removePhoneMask } from './formatters/phone';
26 changes: 26 additions & 0 deletions src/utils/commaline.ts
Original file line number Diff line number Diff line change
@@ -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));
}, '');
}
}
44 changes: 44 additions & 0 deletions tests/commaline.test.ts
Original file line number Diff line number Diff line change
@@ -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('');
});
});