semantic-typescript 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/readme.de.md +335 -0
- package/readme.es.md +335 -0
- package/readme.fr.md +335 -0
- package/readme.jp.md +335 -0
- package/readme.kr.md +335 -0
- package/readme.md +335 -0
- package/readme.tw.md +335 -0
package/package.json
CHANGED
package/readme.de.md
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
# 📘 semantic-typescript
|
|
2
|
+
|
|
3
|
+
Eine leistungsstarke, typsichere Utility-Bibliothek für die **semantische Datenverarbeitung** in TypeScript.
|
|
4
|
+
Sie bietet komponierbare, funktional-programmierende Konstrukte zur Arbeit mit Collections, Streams und Sequenzen – inklusive Unterstützung für Sortieren, Filtern, Gruppieren, Statistik und mehr.
|
|
5
|
+
|
|
6
|
+
Ob Sie **sortierte oder unsortierte Daten** verarbeiten, **statistische Analysen** durchführen oder einfach nur **operationen flüssig verketten** möchten – diese Bibliothek deckt Ihr Bedürfnis ab.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 🧩 Merkmale
|
|
11
|
+
|
|
12
|
+
- ✅ Vollständig **typsichere Generics**
|
|
13
|
+
- ✅ **Funktionale Programmierung** (z. B. map, filter, reduce)
|
|
14
|
+
- ✅ **Semantische Datenströme** (`Semantic<E>`) für **Lazy Evaluation**
|
|
15
|
+
- ✅ **Collector** zum Umwandeln von Streams in konkrete Datenstrukturen
|
|
16
|
+
- ✅ **Sortierte und unsortierte Collectables** – `toUnordered()` ist **am schnellsten (kein Sortieren**
|
|
17
|
+
- ✅ **Sortieren** über `sorted()`, `toOrdered()`, Vergleichsfunktionen
|
|
18
|
+
- ✅ **Statistische Analyse** (`Statistics`, `NumericStatistics`, `BigIntStatistics`)
|
|
19
|
+
- ✅ **Optional<T>** – Monade für sicheres Arbeiten mit potenziell `null` oder `undefined`
|
|
20
|
+
- ✅ **Iteratoren & Generatoren** basiertes Design – ideal auch für große oder asynchrone Daten
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 📦 Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install semantic-typescript
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 🧠 Kernkonzepte
|
|
33
|
+
|
|
34
|
+
### 1. `Optional<T>` – Sicheres Arbeiten mit Nullable-Werten
|
|
35
|
+
|
|
36
|
+
Ein monadisches Container-Objekt für Werte, die `null` oder `undefined` sein können.
|
|
37
|
+
|
|
38
|
+
#### Methoden:
|
|
39
|
+
|
|
40
|
+
| Methode | Beschreibung | Beispiel |
|
|
41
|
+
|--------|-------------|---------|
|
|
42
|
+
| `of(value)` | Wert einpacken (kann null/undefined sein) | `Optional.of(null)` |
|
|
43
|
+
| `ofNullable(v)` | Einpacken, null/undefined erlaubt | `Optional.ofNullable(someVar)` |
|
|
44
|
+
| `ofNonNull(v)` | Einpacken, bei null/undefined wird eine Exception geworfen | `Optional.ofNonNull(5)` |
|
|
45
|
+
| `get()` | Wert auslesen (bei leerem Optional: Exception) | `opt.get()` |
|
|
46
|
+
| `getOrDefault(d)` | Wert auslesen oder Standardwert verwenden | `opt.getOrDefault(0)` |
|
|
47
|
+
| `ifPresent(fn)` | Side-Effect ausführen, wenn Wert vorhanden | `opt.ifPresent(x => console.log(x))` |
|
|
48
|
+
| `map(fn)` | Wert transformieren (wenn vorhanden) | `opt.map(x => x + 1)` |
|
|
49
|
+
| `filter(fn)` | Nur Werte behalten, die den Prädikat erfüllen | `opt.filter(x => x > 0)` |
|
|
50
|
+
| `isEmpty()` | Prüfen, ob das Optional leer ist | `opt.isEmpty()` |
|
|
51
|
+
| `isPresent()` | Prüfen, ob ein Wert vorhanden ist | `opt.isPresent()` |
|
|
52
|
+
|
|
53
|
+
#### Beispiel:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { Optional } from 'semantic-typescript';
|
|
57
|
+
|
|
58
|
+
const value: number | null = Math.random() > 0.5 ? 10 : null;
|
|
59
|
+
|
|
60
|
+
const opt = Optional.ofNullable(value);
|
|
61
|
+
|
|
62
|
+
const result = opt
|
|
63
|
+
.filter(v => v > 5)
|
|
64
|
+
.map(v => v * 2)
|
|
65
|
+
.getOrDefault(0);
|
|
66
|
+
|
|
67
|
+
console.log(result); // 20 oder 0
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
### 2. `Semantic<E>` – Lazy Datenstrom
|
|
73
|
+
|
|
74
|
+
Ein **Lazy, komponierbarer Sequence-Typ**. Ähnlich wie Java Streams oder Kotlin Sequences.
|
|
75
|
+
|
|
76
|
+
Erstellen Sie einen `Semantic`-Datenstrom mit Helfern wie `from()`, `range()`, `iterate()` oder `fill()`.
|
|
77
|
+
|
|
78
|
+
#### Erzeugungsmethoden:
|
|
79
|
+
|
|
80
|
+
| Funktion | Beschreibung | Beispiel |
|
|
81
|
+
|----------|-------------|---------|
|
|
82
|
+
| `from(iterable)` | Aus Array/Set/Iterable erstellen | `from([1, 2, 3])` |
|
|
83
|
+
| `range(start, end, step?)` | Zahlenbereich erzeugen | `range(0, 5)` → 0,1,2,3,4 |
|
|
84
|
+
| `fill(element, count)` | Einen Wert N-mal wiederholen | `fill('a', 3n)` |
|
|
85
|
+
| `iterate(gen)` | Benutzerdefinierten Generator verwenden | `iterate(genFn)` |
|
|
86
|
+
|
|
87
|
+
#### Häufig verwendete Operatoren:
|
|
88
|
+
|
|
89
|
+
| Methode | Beschreibung | Beispiel |
|
|
90
|
+
|--------|-------------|---------|
|
|
91
|
+
| `map(fn)` | Jedes Element transformieren | `.map(x => x * 2)` |
|
|
92
|
+
| `filter(fn)` | Nur Elemente behalten, die den Prädikat erfüllen | `.filter(x => x > 10)` |
|
|
93
|
+
| `limit(n)` | Maximale Anzahl von N Elementen | `.limit(5)` |
|
|
94
|
+
| `skip(n)` | Erste N Elemente überspringen | `.skip(2)` |
|
|
95
|
+
| `distinct()` | Duplikate entfernen (nutzt intern Set) | `.distinct()` |
|
|
96
|
+
| `sorted()` | Elemente sortieren (natürliche Reihenfolge) | `.sorted()` |
|
|
97
|
+
| `sorted(comparator)` | Mit benutzerdefinierter Sortierfunktion | `.sorted((a, b) => a - b)` |
|
|
98
|
+
| `toOrdered()` | Sortieren und `OrderedCollectable` zurückgeben | `.toOrdered()` |
|
|
99
|
+
| `toUnordered()` | **Keine Sortierung** – schnellster Weg | `.toUnordered()` ✅ |
|
|
100
|
+
| `collect(collector)` | Mit einem Collector aggregieren | `.collect(Collector.full(...))` |
|
|
101
|
+
| `toArray()` | In Array umwandeln | `.toArray()` |
|
|
102
|
+
| `toSet()` | In Set umwandeln | `.toSet()` |
|
|
103
|
+
| `toMap(keyFn, valFn)` | In Map umwandeln | `.toMap(x => x.id, x => x)` |
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
### 3. `toUnordered()` – 🚀 Am schnellsten, keine Sortierung
|
|
108
|
+
|
|
109
|
+
Wenn Sie **keine bestimmte Reihenfolge** benötigen und den **schnellsten möglichen Durchsatz** wünschen, verwenden Sie:
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
const fastest = semanticStream.toUnordered();
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
🔥 **Es wird kein Sortieralgorithmus verwendet.**
|
|
116
|
+
Idealerweise bei irrelevanter Reihenfolge und maximalem Performancebedarf.
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### 4. `toOrdered()` und `sorted()` – Sortierte Ausgabe
|
|
121
|
+
|
|
122
|
+
Wenn Sie eine **sortierte Ausgabe** benötigen, verwenden Sie:
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
const ordered = semanticStream.sorted(); // Natürliche Sortierung
|
|
126
|
+
const customSorted = semanticStream.sorted((a, b) => a - b); // Eigene Sortierlogik
|
|
127
|
+
const orderedCollectable = semanticStream.toOrdered(); // Auch sortiert
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
⚠️ Diese Methoden **sortieren die Elemente**, entweder nach natürlicher Ordnung oder mit einem angegebenen Comparator.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
### 5. `Collector<E, A, R>` – Datensammlung / Aggregation
|
|
135
|
+
|
|
136
|
+
Mit Collectors können Sie Streams in **einzelne oder komplexe Strukturen** umwandeln.
|
|
137
|
+
|
|
138
|
+
Eingebaute statische Factorys:
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
Collector.full(identity, accumulator, finisher)
|
|
142
|
+
Collector.shortable(identity, interruptor, accumulator, finisher)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
In der Praxis werden Sie diese meist über die höherwertigen Methoden der `Collectable`-Klassen verwenden.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
### 6. `Collectable<E>` (abstrakte Klasse)
|
|
150
|
+
|
|
151
|
+
Basisklasse für:
|
|
152
|
+
|
|
153
|
+
- `OrderedCollectable<E>` – Sortierte Ausgabe
|
|
154
|
+
- `UnorderedCollectable<E>` – Keine Sortierung, schnellster Weg
|
|
155
|
+
- `WindowCollectable<E>` – Gleitende Fenster
|
|
156
|
+
- `Statistics<E, D>` – Statistische Aggregation
|
|
157
|
+
|
|
158
|
+
#### Häufige Methoden (über Vererbung):
|
|
159
|
+
|
|
160
|
+
| Methode | Beschreibung | Beispiel |
|
|
161
|
+
|--------|-------------|---------|
|
|
162
|
+
| `count()` | Anzahl der Elemente | `.count()` |
|
|
163
|
+
| `toArray()` | In Array umwandeln | `.toArray()` |
|
|
164
|
+
| `toSet()` | In Set umwandeln | `.toSet()` |
|
|
165
|
+
| `toMap(k, v)` | In Map umwandeln | `.toMap(x => x.id, x => x)` |
|
|
166
|
+
| `group(k)` | Nach Schlüssel gruppieren | `.group(x => x.category)` |
|
|
167
|
+
| `findAny()` | Beliebiges passendes Element (Optional) | `.findAny()` |
|
|
168
|
+
| `findFirst()` | Erstes Element (Optional) | `.findFirst()` |
|
|
169
|
+
| `reduce(...)` | Benutzerdefiniertes Reduzieren | `.reduce((a,b) => a + b, 0)` |
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
### 7. `OrderedCollectable<E>` – Sortierte Daten
|
|
174
|
+
|
|
175
|
+
Wenn Sie möchten, dass die Elemente **automatisch sortiert** werden, verwenden Sie diese Klasse.
|
|
176
|
+
|
|
177
|
+
Akzeptiert einen **benutzerdefinierten Comparator** oder nutzt die natürliche Sortierung.
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
const sorted = new OrderedCollectable(stream);
|
|
181
|
+
const customSorted = new OrderedCollectable(stream, (a, b) => b - a);
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
🔒 **Sortierte Ausgabe garantiert.**
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
### 8. `UnorderedCollectable<E>` – Keine Sortierung (🚀 Schnellster)
|
|
189
|
+
|
|
190
|
+
Wenn Ihnen die **Reihenfolge egal** ist und Sie die **beste Performance** wünschen, verwenden Sie:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
const unordered = new UnorderedCollectable(stream);
|
|
194
|
+
// Oder
|
|
195
|
+
const fastest = semanticStream.toUnordered();
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
✅ **Kein Sortieralgorithmus wird ausgeführt**
|
|
199
|
+
✅ **Beste Performance, wenn Reihenfolge keine Rolle spielt**
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
### 9. `Statistics<E, D>` – Statistische Analyse
|
|
204
|
+
|
|
205
|
+
Abstrakte Basisklasse zur Analyse numerischer Daten.
|
|
206
|
+
|
|
207
|
+
#### Unterklassen:
|
|
208
|
+
|
|
209
|
+
- `NumericStatistics<E>` – Für `number`-Werte
|
|
210
|
+
- `BigIntStatistics<E>` – Für `bigint`-Werte
|
|
211
|
+
|
|
212
|
+
##### Häufig verwendete statistische Methoden:
|
|
213
|
+
|
|
214
|
+
| Methode | Beschreibung | Beispiel |
|
|
215
|
+
|--------|-------------|---------|
|
|
216
|
+
| `mean()` | Mittelwert | `.mean()` |
|
|
217
|
+
| `median()` | Median | `.median()` |
|
|
218
|
+
| `mode()` | Modalwert (häufigster Wert) | `.mode()` |
|
|
219
|
+
| `minimum()` | Minimum | `.minimum()` |
|
|
220
|
+
| `maximum()` | Maximum | `.maximum()` |
|
|
221
|
+
| `range()` | Maximum − Minimum | `.range()` |
|
|
222
|
+
| `variance()` | Varianz | `.variance()` |
|
|
223
|
+
| `standardDeviation()` | Standardabweichung | `.standardDeviation()` |
|
|
224
|
+
| `summate()` | Summe aller Werte | `.summate()` |
|
|
225
|
+
| `quantile(q)` | Quantil bei q (0–1) | `.quantile(0.5)` → Median |
|
|
226
|
+
| `frequency()` | Häufigkeit als Map | `.frequency()` |
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## 🧪 Vollständiges Beispiel
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
import { from, toUnordered, toOrdered, sorted, NumericStatistics } from 'semantic-typescript';
|
|
234
|
+
|
|
235
|
+
// Beispiel-Daten
|
|
236
|
+
const numbers = from([10, 2, 8, 4, 5, 6]);
|
|
237
|
+
|
|
238
|
+
// 🚀 Schnellster Weg: keine Sortierung
|
|
239
|
+
const fastest = numbers.toUnordered();
|
|
240
|
+
console.log(fastest.toArray()); // z.B. [10, 2, 8, 4, 5, 6] (wie eingegeben)
|
|
241
|
+
|
|
242
|
+
// 🔢 Natürlich sortiert
|
|
243
|
+
const ordered = numbers.sorted();
|
|
244
|
+
console.log(ordered.toArray()); // [2, 4, 5, 6, 8, 10]
|
|
245
|
+
|
|
246
|
+
// 📊 Statistik auswerten
|
|
247
|
+
const stats = new NumericStatistics(numbers);
|
|
248
|
+
console.log('Mittelwert:', stats.mean());
|
|
249
|
+
console.log('Median:', stats.median());
|
|
250
|
+
console.log('Modalwert:', stats.mode());
|
|
251
|
+
console.log('Bereich:', stats.range());
|
|
252
|
+
console.log('Standardabweichung:', stats.standardDeviation());
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## 🛠️ Hilfsfunktionen
|
|
258
|
+
|
|
259
|
+
Die Bibliothek exportiert auch zahlreiche **Typ-Guards** und **Vergleichsfunktionen**:
|
|
260
|
+
|
|
261
|
+
| Funktion | Zweck |
|
|
262
|
+
|----------|-------|
|
|
263
|
+
| `isString(x)` | Typ-Guard für `string` |
|
|
264
|
+
| `isNumber(x)` | Typ-Guard für `number` |
|
|
265
|
+
| `isBoolean(x)` | Typ-Guard für `boolean` |
|
|
266
|
+
| `isIterable(x)` | Prüft, ob ein Objekt iterierbar ist |
|
|
267
|
+
| `useCompare(a, b)` | Universelle Vergleichsfunktion |
|
|
268
|
+
| `useRandom(x)` | Pseudo-Zufallszahlengenerator (spielerisch) |
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## 🧩 Erweitert: Eigene Generatoren & Fenster
|
|
273
|
+
|
|
274
|
+
Sie können eigene **Generatoren** für kontrollierte oder unendliche Datenströme erstellen:
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
const gen = (accept: BiConsumer<number, bigint>, interrupt: Predicate<number>) => {
|
|
278
|
+
for (let i = 0; i < 10; i++) {
|
|
279
|
+
accept(i, BigInt(i));
|
|
280
|
+
if (i === 5) interrupt(i);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
const s = new Semantic(gen);
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Oder **gleitende Fenster** verwenden:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
const windowed = ordered.slide(3n, 2n); // Fenstergröße 3, Schritt 2
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## 📄 Lizenz
|
|
296
|
+
|
|
297
|
+
Dieses Projekt steht unter der **MIT-Lizenz** – kostenlos für kommerzielle und private Nutzung.
|
|
298
|
+
|
|
299
|
+
---
|
|
300
|
+
|
|
301
|
+
## 🙌 Mitwirken
|
|
302
|
+
|
|
303
|
+
Pull Requests, Issues und Ideen sind willkommen!
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## 🚀 Schnellstart-Zusammenfassung
|
|
308
|
+
|
|
309
|
+
| Aufgabe | Methode |
|
|
310
|
+
|--------|---------|
|
|
311
|
+
| Null-sicheres Arbeiten | `Optional<T>` |
|
|
312
|
+
| Stream erstellen | `from([...])`, `range()`, `fill()` |
|
|
313
|
+
| Daten transformieren | `map()`, `filter()` |
|
|
314
|
+
| Daten sortieren | `sorted()`, `toOrdered()` |
|
|
315
|
+
| Keine Sortierung (schnell) | `toUnordered()` ✅ |
|
|
316
|
+
| Gruppieren / Aggregieren | `toMap()`, `group()`, `Collector` |
|
|
317
|
+
| Statistik | `NumericStatistics`, `mean()`, `median()` usw. |
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## 🔗 Links
|
|
322
|
+
|
|
323
|
+
- 📦 npm: https://www.npmjs.com/package/semantic-typescript
|
|
324
|
+
- 🐙 GitHub: https://github.com/eloyhere/semantic-typescript
|
|
325
|
+
- 📘 Dokumentation: Siehe Quellcode / Typdefinitionen
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
**Genießen Sie komponierbares, typsicheres und funktionales Datenhandling in TypeScript.** 🚀
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
✅ **Wichtig:**
|
|
334
|
+
- `toUnordered()` → **Keine Sortierung, schnellster Weg**
|
|
335
|
+
- Alle anderen (z. B. `sorted()`, `toOrdered()`) → **Sortieren die Daten**
|
package/readme.es.md
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
# 📘 semantic-typescript
|
|
2
|
+
|
|
3
|
+
Una poderosa biblioteca de utilidades para **procesamiento semántico de datos** en TypeScript, completamente **segura y tipada**.
|
|
4
|
+
Proporciona construcciones funcionales compuestas para trabajar con colecciones, flujos y secuencias — con soporte para ordenar, filtrar, agrupar, realizar análisis estadísticos y más.
|
|
5
|
+
|
|
6
|
+
Ya sea que estés procesando **datos ordenados o no ordenados**, realizando **análisis estadísticos**, o simplemente **encadenando operaciones de forma fluida**, esta biblioteca está diseñada para cubrir todas tus necesidades.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 🧩 Características
|
|
11
|
+
|
|
12
|
+
- ✅ **Genéricos tipados de forma segura** en toda la biblioteca
|
|
13
|
+
- ✅ Estilo **funcional** (map, filter, reduce, etc.)
|
|
14
|
+
- ✅ **Flujos de datos semánticos** (`Semantic<E>`) para evaluación diferida (lazy)
|
|
15
|
+
- ✅ **Coleccionadores (Collectors)** para transformar flujos en estructuras concretas
|
|
16
|
+
- ✅ **Collectables ordenados y no ordenados** — `toUnordered()` es **el más rápido (sin ordenar)**
|
|
17
|
+
- ✅ **Soporte para ordenar** mediante `sorted()`, `toOrdered()`, y comparadores personalizados
|
|
18
|
+
- ✅ **Análisis estadístico** (`Statistics`, `NumericStatistics`, `BigIntStatistics`)
|
|
19
|
+
- ✅ **Optional<T>** — monada para manejar valores nulos de forma segura
|
|
20
|
+
- ✅ Diseño basado en **iteradores y generadores** — ideal para grandes volúmenes o datos asíncronos
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 📦 Instalación
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install semantic-typescript
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 🧠 Conceptos clave
|
|
33
|
+
|
|
34
|
+
### 1. `Optional<T>` — Manejo seguro de valores nulos
|
|
35
|
+
|
|
36
|
+
Un contenedor monádico para valores que pueden ser `null` o `undefined`.
|
|
37
|
+
|
|
38
|
+
#### Métodos:
|
|
39
|
+
|
|
40
|
+
| Método | Descripción | Ejemplo |
|
|
41
|
+
|--------|-------------|---------|
|
|
42
|
+
| `of(value)` | Envolver un valor (puede ser nulo) | `Optional.of(null)` |
|
|
43
|
+
| `ofNullable(v)` | Envolver, permite valores nulos | `Optional.ofNullable(someVar)` |
|
|
44
|
+
| `ofNonNull(v)` | Envolver, lanza excepción si es nulo/undefined | `Optional.ofNonNull(5)` |
|
|
45
|
+
| `get()` | Obtener el valor (o lanzar excepción si está vacío) | `opt.get()` |
|
|
46
|
+
| `getOrDefault(d)` | Obtener el valor o un valor por defecto | `opt.getOrDefault(0)` |
|
|
47
|
+
| `ifPresent(fn)` | Ejecutar un efecto secundario si hay valor | `opt.ifPresent(x => console.log(x))` |
|
|
48
|
+
| `map(fn)` | Transformar el valor si existe | `opt.map(x => x + 1)` |
|
|
49
|
+
| `filter(fn)` | Conservar el valor solo si cumple el predicado | `opt.filter(x => x > 0)` |
|
|
50
|
+
| `isEmpty()` | Verificar si está vacío | `opt.isEmpty()` |
|
|
51
|
+
| `isPresent()` | Verificar si tiene un valor | `opt.isPresent()` |
|
|
52
|
+
|
|
53
|
+
#### Ejemplo:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { Optional } from 'semantic-typescript';
|
|
57
|
+
|
|
58
|
+
const value: number | null = Math.random() > 0.5 ? 10 : null;
|
|
59
|
+
|
|
60
|
+
const opt = Optional.ofNullable(value);
|
|
61
|
+
|
|
62
|
+
const result = opt
|
|
63
|
+
.filter(v => v > 5)
|
|
64
|
+
.map(v => v * 2)
|
|
65
|
+
.getOrDefault(0);
|
|
66
|
+
|
|
67
|
+
console.log(result); // 20 o 0
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
### 2. `Semantic<E>` — Flujo de datos diferido
|
|
73
|
+
|
|
74
|
+
Un **flujo secuencial diferido y compuesto**. Similar a Java Streams o Kotlin Sequences.
|
|
75
|
+
|
|
76
|
+
Puedes crear un `Semantic` usando funciones como `from()`, `range()`, `iterate()` o `fill()`.
|
|
77
|
+
|
|
78
|
+
#### Creadores:
|
|
79
|
+
|
|
80
|
+
| Función | Descripción | Ejemplo |
|
|
81
|
+
|--------|-------------|---------|
|
|
82
|
+
| `from(iterable)` | Crear desde un Array, Set, Iterable | `from([1, 2, 3])` |
|
|
83
|
+
| `range(start, end, step?)` | Generar una secuencia de números | `range(0, 5)` → 0,1,2,3,4 |
|
|
84
|
+
| `fill(element, count)` | Repetir un elemento N veces | `fill('a', 3n)` |
|
|
85
|
+
| `iterate(gen)` | Usar una función generadora personalizada | `iterate(genFn)` |
|
|
86
|
+
|
|
87
|
+
#### Operadores comunes:
|
|
88
|
+
|
|
89
|
+
| Método | Descripción | Ejemplo |
|
|
90
|
+
|--------|-------------|---------|
|
|
91
|
+
| `map(fn)` | Transformar cada elemento | `.map(x => x * 2)` |
|
|
92
|
+
| `filter(fn)` | Conservar elementos que cumplen el predicado | `.filter(x => x > 10)` |
|
|
93
|
+
| `limit(n)` | Limitar a los primeros N elementos | `.limit(5)` |
|
|
94
|
+
| `skip(n)` | Saltar los primeros N elementos | `.skip(2)` |
|
|
95
|
+
| `distinct()` | Eliminar duplicados (usa Set por defecto) | `.distinct()` |
|
|
96
|
+
| `sorted()` | Ordenar elementos (orden natural) | `.sorted()` |
|
|
97
|
+
| `sorted(comparator)` | Ordenar con un comparador personalizado | `.sorted((a, b) => a - b)` |
|
|
98
|
+
| `toOrdered()` | Ordenar y devolver un `OrderedCollectable` | `.toOrdered()` |
|
|
99
|
+
| `toUnordered()` | **Sin ordenar** — el más rápido | `.toUnordered()` ✅ |
|
|
100
|
+
| `collect(collector)` | Agregar usando un `Collector` | `.collect(Collector.full(...))` |
|
|
101
|
+
| `toArray()` | Convertir a Array | `.toArray()` |
|
|
102
|
+
| `toSet()` | Convertir a Set | `.toSet()` |
|
|
103
|
+
| `toMap(keyFn, valFn)` | Convertir a Map | `.toMap(x => x.id, x => x)` |
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
### 3. `toUnordered()` — 🚀 El más rápido, sin ordenar
|
|
108
|
+
|
|
109
|
+
Si **no necesitas orden** y quieres el **máximo rendimiento**, utiliza:
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
const fastest = semanticStream.toUnordered();
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
🔥 **No se aplica ningún algoritmo de ordenamiento.**
|
|
116
|
+
Ideal cuando el orden no importa y la velocidad es prioritaria.
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### 4. `toOrdered()` y `sorted()` — Resultados ordenados
|
|
121
|
+
|
|
122
|
+
Si necesitas un **resultado ordenado**, puedes usar:
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
const ordered = semanticStream.sorted(); // Orden natural
|
|
126
|
+
const customSorted = semanticStream.sorted((a, b) => a - b); // Comparador personalizado
|
|
127
|
+
const orderedCollectable = semanticStream.toOrdered(); // También ordenado
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
⚠️ Estos métodos **ordenarán los elementos**, usando orden natural o el comparador dado.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
### 5. `Collector<E, A, R>` — Agregación de datos
|
|
135
|
+
|
|
136
|
+
Los **colectores** te permiten **reducir un flujo a una estructura única o compleja**.
|
|
137
|
+
|
|
138
|
+
Existen fábricas estáticas como:
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
Collector.full(identity, accumulator, finisher)
|
|
142
|
+
Collector.shortable(identity, interruptor, accumulator, finisher)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Pero normalmente los usarás a través de métodos de alto nivel en las clases `Collectable`.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
### 6. `Collectable<E>` (clase abstracta)
|
|
150
|
+
|
|
151
|
+
Clase base para:
|
|
152
|
+
|
|
153
|
+
- `OrderedCollectable<E>` — Resultados ordenados
|
|
154
|
+
- `UnorderedCollectable<E>` — Sin ordenar, el más rápido
|
|
155
|
+
- `WindowCollectable<E>` — Ventanas deslizantes
|
|
156
|
+
- `Statistics<E, D>` — Estadísticas agregadas
|
|
157
|
+
|
|
158
|
+
#### Métodos comunes (heredados):
|
|
159
|
+
|
|
160
|
+
| Método | Descripción | Ejemplo |
|
|
161
|
+
|--------|-------------|---------|
|
|
162
|
+
| `count()` | Contar elementos | `.count()` |
|
|
163
|
+
| `toArray()` | Convertir a Array | `.toArray()` |
|
|
164
|
+
| `toSet()` | Convertir a Set | `.toSet()` |
|
|
165
|
+
| `toMap(k, v)` | Convertir a Map | `.toMap(x => x.id, x => x)` |
|
|
166
|
+
| `group(k)` | Agrupar por clave | `.group(x => x.category)` |
|
|
167
|
+
| `findAny()` | Encontrar cualquier elemento (Optional) | `.findAny()` |
|
|
168
|
+
| `findFirst()` | Encontrar el primer elemento (Optional) | `.findFirst()` |
|
|
169
|
+
| `reduce(...)` | Reducción personalizada | `.reduce((a,b) => a + b, 0)` |
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
### 7. `OrderedCollectable<E>` — Datos ordenados
|
|
174
|
+
|
|
175
|
+
Si deseas que los elementos estén **ordenados automáticamente**, usa esta clase.
|
|
176
|
+
|
|
177
|
+
Acepta un **comparador personalizado** o el orden natural.
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
const sorted = new OrderedCollectable(stream);
|
|
181
|
+
const customSorted = new OrderedCollectable(stream, (a, b) => b - a);
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
🔒 **El orden está garantizado.**
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
### 8. `UnorderedCollectable<E>` — Sin ordenar (🚀 Más rápido)
|
|
189
|
+
|
|
190
|
+
Si **no te importa el orden** y buscas el **mejor rendimiento**, usa:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
const unordered = new UnorderedCollectable(stream);
|
|
194
|
+
// O
|
|
195
|
+
const fastest = semanticStream.toUnordered();
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
✅ **No se ejecuta ningún algoritmo de ordenamiento**
|
|
199
|
+
✅ **Mejor rendimiento cuando el orden no importa**
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
### 9. `Statistics<E, D>` — Análisis estadístico
|
|
204
|
+
|
|
205
|
+
Clase abstracta para analizar datos numéricos.
|
|
206
|
+
|
|
207
|
+
#### Subclases:
|
|
208
|
+
|
|
209
|
+
- `NumericStatistics<E>` — Para valores `number`
|
|
210
|
+
- `BigIntStatistics<E>` — Para valores `bigint`
|
|
211
|
+
|
|
212
|
+
##### Métodos estadísticos comunes:
|
|
213
|
+
|
|
214
|
+
| Método | Descripción | Ejemplo |
|
|
215
|
+
|--------|-------------|---------|
|
|
216
|
+
| `mean()` | Media | `.mean()` |
|
|
217
|
+
| `median()` | Mediana | `.median()` |
|
|
218
|
+
| `mode()` | Moda (valor más frecuente) | `.mode()` |
|
|
219
|
+
| `minimum()` | Mínimo | `.minimum()` |
|
|
220
|
+
| `maximum()` | Máximo | `.maximum()` |
|
|
221
|
+
| `range()` | Rango (máximo - mínimo) | `.range()` |
|
|
222
|
+
| `variance()` | Varianza | `.variance()` |
|
|
223
|
+
| `standardDeviation()` | Desviación estándar | `.standardDeviation()` |
|
|
224
|
+
| `summate()` | Suma total | `.summate()` |
|
|
225
|
+
| `quantile(q)` | Valor en el percentil q (0–1) | `.quantile(0.5)` → mediana |
|
|
226
|
+
| `frequency()` | Frecuencia como Map | `.frequency()` |
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## 🧪 Ejemplo completo
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
import { from, toUnordered, toOrdered, sorted, NumericStatistics } from 'semantic-typescript';
|
|
234
|
+
|
|
235
|
+
// Datos de ejemplo
|
|
236
|
+
const numbers = from([10, 2, 8, 4, 5, 6]);
|
|
237
|
+
|
|
238
|
+
// 🚀 Más rápido: sin ordenar
|
|
239
|
+
const fastest = numbers.toUnordered();
|
|
240
|
+
console.log(fastest.toArray()); // Ej: [10, 2, 8, 4, 5, 6] (orden original)
|
|
241
|
+
|
|
242
|
+
// 🔢 Orden natural
|
|
243
|
+
const ordered = numbers.sorted();
|
|
244
|
+
console.log(ordered.toArray()); // [2, 4, 5, 6, 8, 10]
|
|
245
|
+
|
|
246
|
+
// 📊 Estadísticas
|
|
247
|
+
const stats = new NumericStatistics(numbers);
|
|
248
|
+
console.log('Media:', stats.mean());
|
|
249
|
+
console.log('Mediana:', stats.median());
|
|
250
|
+
console.log('Moda:', stats.mode());
|
|
251
|
+
console.log('Rango:', stats.range());
|
|
252
|
+
console.log('Desviación estándar:', stats.standardDeviation());
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## 🛠️ Funciones útiles
|
|
258
|
+
|
|
259
|
+
La librería también exporta varias **guardas de tipo (type guards)** y **herramientas de comparación**:
|
|
260
|
+
|
|
261
|
+
| Función | Propósito |
|
|
262
|
+
|--------|-----------|
|
|
263
|
+
| `isString(x)` | Guarda de tipo para `string` |
|
|
264
|
+
| `isNumber(x)` | Guarda de tipo para `number` |
|
|
265
|
+
| `isBoolean(x)` | Guarda de tipo para `boolean` |
|
|
266
|
+
| `isIterable(x)` | Comprueba si un objeto es iterable |
|
|
267
|
+
| `useCompare(a, b)` | Función de comparación universal |
|
|
268
|
+
| `useRandom(x)` | Generador de números aleatorios (divertido) |
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## 🧩 Avanzado: Generadores personalizados y ventanas
|
|
273
|
+
|
|
274
|
+
Puedes crear **generadores personalizados** para flujos controlados o infinitos:
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
const gen = (accept: BiConsumer<number, bigint>, interrupt: Predicate<number>) => {
|
|
278
|
+
for (let i = 0; i < 10; i++) {
|
|
279
|
+
accept(i, BigInt(i));
|
|
280
|
+
if (i === 5) interrupt(i);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
const s = new Semantic(gen);
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
O usar **ventanas deslizantes (sliding windows)**:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
const windowed = ordered.slide(3n, 2n); // Ventanas de tamaño 3, salto de 2
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## 📄 Licencia
|
|
296
|
+
|
|
297
|
+
Este proyecto está bajo la licencia **MIT** — libre para uso comercial y personal.
|
|
298
|
+
|
|
299
|
+
---
|
|
300
|
+
|
|
301
|
+
## 🙌 Contribuir
|
|
302
|
+
|
|
303
|
+
¡Pull requests, issues y sugerencias son bienvenidos!
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## 🚀 Resumen rápido
|
|
308
|
+
|
|
309
|
+
| Tarea | Método |
|
|
310
|
+
|-------|--------|
|
|
311
|
+
| Manejar nulos con seguridad | `Optional<T>` |
|
|
312
|
+
| Crear un flujo | `from([...])`, `range()`, `fill()` |
|
|
313
|
+
| Transformar datos | `map()`, `filter()` |
|
|
314
|
+
| Ordenar datos | `sorted()`, `toOrdered()` |
|
|
315
|
+
| Sin ordenar (más rápido) | `toUnordered()` ✅ |
|
|
316
|
+
| Agrupar / Agregar | `toMap()`, `group()`, `Collector` |
|
|
317
|
+
| Estadísticas | `NumericStatistics`, `mean()`, `median()`, etc. |
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## 🔗 Enlaces
|
|
322
|
+
|
|
323
|
+
- 📦 npm: https://www.npmjs.com/package/semantic-typescript
|
|
324
|
+
- 🐙 GitHub: https://github.com/eloyhere/semantic-typescript
|
|
325
|
+
- 📘 Documentación: Ver código fuente / definiciones de tipo
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
**Disfruta del procesamiento de datos funcional, seguro y compuesto en TypeScript.** 🚀
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
✅ **Recuerda:**
|
|
334
|
+
- `toUnordered()` → **Sin ordenar, más rápido**
|
|
335
|
+
- Los demás (`sorted()`, `toOrdered()`, etc.) → **Ordenan los datos**
|