semantic-typescript 0.5.3 → 0.7.0

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/readme.md CHANGED
@@ -1,1066 +1,213 @@
1
- # Semantic-TypeScript Stream Processing Library
2
-
3
- ## Introduction
4
-
5
- **Semantic-TypeScript: A Paradigm-Shifting Stream Processing Library for the Modern Web**
6
-
7
- Semantic-TypeScript represents a significant advancement in stream processing technology, synthesising the most effective concepts from JavaScript GeneratorFunction, Java Stream, and MySQL Index paradigms. Its foundational design principle is centred on constructing exceptionally efficient data processing pipelines through sophisticated data indexing methodologies. The library delivers a rigorously type-safe, functionally pure streaming operation experience specifically engineered for contemporary front-end development.
8
-
9
- In contrast to conventional synchronous processing architectures, Semantic-TypeScript implements a fully asynchronous processing model. During data stream generation, the temporal reception of data at the terminal is determined exclusively by the upstream invocation of the `accept` and `interrupt` callback mechanisms. This deliberate architectural choice enables the library to handle with exceptional grace:
10
-
11
- - **Real-time data streams** with deterministic latency characteristics
12
- - **Large-scale datasets** through memory-efficient processing pipelines
13
- - **Asynchronous data sources** with guaranteed consistency and reliability
14
-
15
- The library's innovative approach fundamentally reimagines how developers interact with streaming data, providing both unprecedented performance characteristics and developer ergonomics in a single, cohesive package.
16
-
17
- ### Why Choose Semantic-TypeScript?
18
-
19
- Selecting the right library for data stream processing in a TypeScript project involves balancing performance, developer experience, and architectural fit. Semantic-TypeScript is engineered to excel across all these dimensions, offering a paradigm-shifting approach for the modern web. Here’s why it stands out.
20
-
21
- #### 1. **A Unified, Type-Safe Paradigm for Streams**
22
- Semantic-TypeScript synthesises the most effective concepts from **JavaScript GeneratorFunctions**, **Java Streams API**, and **database indexing strategies**. It provides a consistent, declarative API for processing any data sequencebe it static arrays, real-time events, or asynchronous chunks—while leveraging TypeScript's full power to ensure end-to-end type safety. This eliminates a whole class of runtime errors and transforms stream manipulation into a predictable, compiler-verified activity.
23
-
24
- #### 2. **Uncompromising Performance with Intelligent Laziness**
25
- At its core, the library is built on **lazy evaluation**. Operations like `filter`, `map`, and `flatMap` merely compose a processing pipeline; no work is done until a terminal operation (like `collect` or `toArray`) is invoked. This is coupled with **short-circuiting** capabilities (via operations like `limit`, `anyMatch`, or custom `interruptor` functions), which allows the processing to stop early when the result is known, dramatically improving efficiency for large or infinite streams.
26
-
27
- #### 3. **Architectural Distinction: `Semantic<E>` vs. `Collectable<E>`**
28
- This library introduces a crucial architectural separation that others often lack:
29
- * **`Semantic<E>`**: Represents the abstract, lazy stream definition—the "blueprint" of your data transformation. It is immutable and composable.
30
- * **`Collectable<E>`**: Represents a materialised, executable view of the stream, offering all terminal operations.
31
-
32
- This separation enforces a clear mental model and allows for optimisations (e.g., an `UnorderedCollectable` can skip expensive sorting steps if order is not required).
33
-
34
- #### 4. **The Power of the `Collector<E, A, R>` Pattern**
35
- Inspired by Java, the `Collector` pattern is the engine of flexibility. It decouples the *specification* of how to accumulate stream elements from the *execution* of the stream itself. The library provides a rich set of built-in collectors (`useToArray`, `useGroupBy`, `useSummate`, etc.) for everyday tasks, while the pattern makes it trivial to implement your own complex, reusable reduction logic. This is far more powerful and composable than a fixed set of terminal methods.
36
-
37
- #### 5. **First-Class Support for Modern Web & Async Data**
38
- Semantic-TypeScript is designed for contemporary front-end and Node.js development. It offers native factory methods for modern web sources:
39
- * `from(iterable)`, `range()` for static data.
40
- * `interval()`, `animationFrame()` for time-based streams.
41
- * `blob()` for chunked binary data processing.
42
- * `websocket()` for real-time message streams.
43
- Its foundational support for both `Iterable` and `AsyncIterable` protocols means it handles synchronous and asynchronous data flows with the same elegant API.
44
-
45
- #### 6. **Beyond Basic Aggregation: Built-in Statistical Analysis**
46
- Move beyond simple sums and averages. The library provides dedicated `NumericStatistics` and `BigIntStatistics` classes, offering immediate access to advanced statistical measures directly from your streams—**variance, standard deviation, median, quantiles, skewness, and kurtosis**. This turns complex data analysis into a one-liner, saving you from manual implementation or integrating another specialised library.
47
-
48
- #### 7. **Designed for Developer Ergonomics**
49
- * **Fluent, Chainable API**: Write complex data pipelines as readable, sequential chains of operations.
50
- * **Comprehensive Utility Suite**: Comes with essential guards (`isOptional`, `isSemantic`), type-safe utilities (`useCompare`, `useTraverse`), and functional interfaces out of the box.
51
- * **`Optional<T>` Integration**: Models the absence of a value safely, eliminating null-pointer concerns in find operations.
52
- * **Performance Guidance**: The documentation clearly guides you on when to use `toUnordered()` (for maximum speed) versus `toOrdered()` (when sequence matters).
53
-
54
- #### 8. **Robust, Community-Ready Foundation**
55
- As an open-source library hosted on **GitHub** and distributed via **npm**, it is built for real-world use. The extensive documentation, complete with time/space complexity annotations and practical examples, lowers the learning curve and provides clarity for performance-sensitive applications.
56
-
57
- **In summary, choose Semantic-TypeScript if you seek a rigorously designed, type-safe, and high-performance stream processing library that brings the power of enterprise-level data transformation patterns to the TypeScript ecosystem, without compromising on the idioms and needs of modern web development.**
58
-
59
- ## Installation
60
-
61
- ```bash
62
- npm install semantic-typescript
63
- ```
64
-
65
- ## Basic Types
66
-
67
- | Type | Description |
68
- |------|-------------|
69
- | `Invalid<T>` | Type that extends `null` or `undefined` |
70
- | `Valid<T>` | Type that excludes `null` and `undefined` |
71
- | `MaybeInvalid<T>` | Type that is either `T` or `null` or `undefined` |
72
- | `MaybeUndefined<T>` | Type that is either `T` or `undefined` |
73
- | `MaybeNull<T>` | Type that is either `T` or `null` |
74
- | `Type` | String literal type representing JavaScript type names |
75
- | `Primitive` | Type representing all primitive JavaScript values |
76
- | `MaybePrimitive<T>` | Type that is either `T` or a primitive value |
77
- | `AsyncFunction` | Type representing an asynchronous function returning a Promise |
78
- | `DeepPropertyKey<T extends object>` | Recursive type for nested object keys |
79
- | `DeepPropertyValue<T extends object>` | Recursive type for nested object values |
80
-
81
- ## Functional Interfaces
82
-
83
- | Interface | Description |
84
- |-----------|-------------|
85
- | `Constructor<T>` | Class constructor that creates instances of type `T` |
86
- | `Runnable` | Function with no parameters and no return value |
87
- | `Supplier<R>` | Function with no parameters returning `R` |
88
- | `Functional<T, R>` | Function that takes `T` and returns `R` |
89
- | `Predicate<T>` | Function that takes `T` and returns a boolean |
90
- | `BiFunctional<T, U, R>` | Function that takes `T` and `U` and returns `R` |
91
- | `BiPredicate<T, U>` | Function that takes `T` and `U` and returns a boolean |
92
- | `TriPredicate<T, U, V>` | Function that takes `T`, `U`, and `V` and returns a boolean |
93
- | `Comparator<T>` | Function that compares two values of type `T` and returns a number |
94
- | `TriFunctional<T, U, V, R>` | Function that takes `T`, `U`, and `V` and returns `R` |
95
- | `Consumer<T>` | Function that takes `T` and returns nothing |
96
- | `BiConsumer<T, U>` | Function that takes `T` and `U` and returns nothing |
97
- | `TriConsumer<T, U, V>` | Function that takes `T`, `U`, and `V` and returns nothing |
98
- | `Generator<T>` | Overloaded function type for generating values with callbacks |
99
- | `Indexed<E>` | Interface containing an element and its index |
100
-
101
- ```typescript
102
- // Type usage examples
103
- let predicate: Predicate<number> = (n: number): boolean => n > 0;
104
- let mapper: Functional<string, number> = (text: string): number => text.length;
105
- let comparator: Comparator<number> = (a: number, b: number): number => a - b;
106
- ```
107
-
108
- ## Validation Functions
109
-
110
- | Function | Description | Time Complexity | Space Complexity |
111
- |------|------|------------|------------|
112
- | `validate<T>(t: MaybeInvalid<T>): t is T` | Validate value is not null or undefined | O(1) | O(1) |
113
- | `invalidate<T>(t: MaybeInvalid<T>): t is null \| undefined` | Validate value is null or undefined | O(1) | O(1) |
114
- | `typeOf<T>(t: T): Type` | Returns the type name of a value, distinguishing null from objects | O(1) | O(1) |
115
-
116
- ## Type Guards
117
-
118
- | Function | Description | Time Complexity | Space Complexity |
119
- |----------|-------------|-----------------|------------------|
120
- | `isBoolean(target: unknown): target is boolean` | Checks if value is a boolean | O(1) | O(1) |
121
- | `isString(target: unknown): target is string` | Checks if value is a string | O(1) | O(1) |
122
- | `isNumber(target: unknown): target is number` | Checks if value is a finite, non-NaN number | O(1) | O(1) |
123
- | `isFunction(target: unknown): target is Function` | Checks if value is a function | O(1) | O(1) |
124
- | `isObject(target: unknown): target is object` | Checks if value is a non-null object | O(1) | O(1) |
125
- | `isSymbol(target: unknown): target is symbol` | Checks if value is a symbol | O(1) | O(1) |
126
- | `isBigInt(target: unknown): target is bigint` | Checks if value is a bigint | O(1) | O(1) |
127
- | `isPrimitive(target: MaybePrimitive<unknown>): target is Primitive` | Checks if value is any primitive type | O(1) | O(1) |
128
- | `isAsyncIterable(target: unknown): target is Iterable<unknown>` | Checks if value is async iterable | O(1) | O(1) |
129
- | `isIterable(target: unknown): target is Iterable<unknown>` | Checks if value is iterable | O(1) | O(1) |
130
- | `isSemantic(target: unknown): target is Semantic<unknown>` | Checks if value is a Semantic | O(1) | O(1) |
131
- | `isCollector(target: unknown): target is Collector<unknown, unknown, unknown>` | Checks if value is a Collector | O(1) | O(1) |
132
- | `isCollectable(target: unknown): target is Collectable<unknown>` | Checks if value is a Collectable | O(1) | O(1) |
133
- | `isOrderedCollectable(target: unknown): target is OrderedCollectable<unknown>` | Checks if value is an OrderedCollectable | O(1) | O(1) |
134
- | `isWindowCollectable(target: unknown): target is WindowCollectable<unknown>` | Checks if value is a WindowCollectable | O(1) | O(1) |
135
- | `isUnorderedCollectable(target: unknown): target is UnorderedCollectable<unknown>` | Checks if value is an UnorderedCollectable | O(1) | O(1) |
136
- | `isStatistics(target: unknown): target is Statistics<unknown, number \| bigint>` | Checks if value is a Statistics | O(1) | O(1) |
137
- | `isNumericStatistics(target: unknown): target is Statistics<unknown, number \| bigint>` | Checks if value is a NumericStatistics | O(1) | O(1) |
138
- | `isBigIntStatistics(target: unknown): target is Statistics<unknown, number \| bigint>` | Checks if value is a BigIntStatistics | O(1) | O(1) |
139
- | `isSemanticMap(target: unknown): target is SemanticMap<unknown, unknown>` | Checks if value is a SemanticMap | O(1) | O(1) |
140
- | `isHashMap(target: unknown): target is HashMap<unknown, unknown>` | Checks if value is a HashMap | O(1) | O(1) |
141
- | `isHashSet(target: unknown): target is HashSet<unknown>` | Checks if value is a HashSet | O(1) | O(1) |
142
- | `isNode(target: unknown): target is Node<unknown, any>` | Checks if value is a Node | O(1) | O(1) |
143
- | `isLinearNode(target: unknown): target is LinearNode<unknown>` | Checks if value is a LinearNode | O(1) | O(1) |
144
- | `isBinaryNode(target: unknown): target is BinaryNode<unknown, any>` | Checks if value is a BinaryNode | O(1) | O(1) |
145
- | `isRedBlackNode(target: unknown): target is BinaryNode<unknown, any>` | Checks if value is a RedBlackNode | O(1) | O(1) |
146
- | `isTree(target: unknown): target is Node<unknown, any>` | Checks if value is a Tree (Linear or Binary Node) | O(1) | O(1) |
147
- | `isBinaryTree(target: unknown): target is Node<unknown, any>` | Checks if value is a BinaryTree | O(1) | O(1) |
148
- | `isRedBlackTree(target: unknown): target is Node<unknown, any>` | Checks if value is a RedBlackTree | O(1) | O(1) |
149
- | `isOptional<T>(target: unknown): target is Optional<T>` | Checks if value is an Optional | O(1) | O(1) |
150
- | `isPromise(target: unknown): target is Promise<unknown>` | Checks if value is a Promise | O(1) | O(1) |
151
- | `isAsyncFunction(target: unknown): target is AsyncFunction` | Checks if value is an AsyncFunction | O(1) | O(1) |
152
- | `isGeneratorFunction(target: unknown): target is Generator<unknown, unknown, unknown>` | Checks if value is a GeneratorFunction | O(1) | O(1) |
153
- | `isAsyncGeneratorFunction(target: unknown): target is AsyncGenerator<unknown, unknown, unknown>` | Checks if value is an AsyncGeneratorFunction | O(1) | O(1) |
154
- | `isWindow(target: unknown): target is Window` | Checks if value is a Window object | O(1) | O(1) |
155
- | `isDocument(target: unknown): target is Document` | Checks if value is a Document object | O(1) | O(1) |
156
- | `isHTMLElemet(target: unknown): target is HTMLElement` | Checks if value is an HTMLElement | O(1) | O(1) |
157
-
158
- ```typescript
159
- // Type guard usage examples
160
- let value: unknown = "hello";
161
-
162
- if (isString(value)) {
163
- console.log(value.length); // Type-safe, value inferred as string
164
- }
165
-
166
- if (isOptional(someValue)) {
167
- someValue.ifPresent((value): void => console.log(value));
168
- }
169
-
170
- if(isIterable(value)){
171
- // Type-safe, now it's an iterable object.
172
- for(let item of value){
173
- console.log(item);
174
- }
175
- }
176
- ```
177
-
178
- ## Hooks
179
-
180
- | Hook | Description | Time Complexity | Space Complexity |
181
- |--------|-------------|-----------------|------------------|
182
- | `useCompare<T>(t1: T, t2: T)` | Compares two values of the same type, returning a number indicating their relative order (negative if t1 < t2, zero if equal, positive if t1 > t2). | O(1) for primitive types, O(n) for objects (depends on valueOf/toString) | O(1) |
183
- | `useRandom<T = number \| bigint>(index: T)` | Generates a deterministic pseudo-random number based on the Van der Corput sequence, golden ratio, and LCG, returning a value of the same type as input (currently only supports number). | O(log n) where n is the input number | O(1) |
184
- | `useTraverse<T extends object>(t: T, callback: UseTraverseCallback<T>)` | Recursively traverses all enumerable properties of an object, invoking the callback for each property. | O(n) where n is total number of properties | O(d) where d is maximum recursion depth |
185
- | `useTraverse<T extends object>(t: T, callback: UseTraversePathCallback<T>)` | Recursively traverses all enumerable properties of an object, invoking the callback with the property key, value, and current path. | O(n) where n is total number of properties | O(d) where d is maximum recursion depth |
186
- | `useGenerator<E>(iterable: Iterable<E>)` | Converts an iterable into a generator function compatible with Semantic's generator interface. | O(1) for setup, iteration depends on source | O(1) |
187
- | `useArrange<E>(source: Iterable<E>)` | Creates a generator that yields elements from the source in their original order. | O(n) for collecting elements | O(n) where n is number of elements |
188
- | `useArrange<E>(source: Iterable<E>, comparator: Comparator<E>)` | Creates a generator that yields elements from the source sorted according to the comparator. | O(n log n) for sorting | O(n) where n is number of elements |
189
- | `useArrange<E>(source: Generator<E>)` | Creates a generator that yields elements from the source generator in their original order. | O(n) for collecting elements | O(n) where n is number of elements |
190
- | `useArrange<E>(source: Generator<E>, comparator: Comparator<E>)` | Creates a generator that yields elements from the source generator sorted according to the comparator. | O(n log n) for sorting | O(n) where n is number of elements |
191
- | `useToNumber<T = unknown>(target: T)` | Converts any value to a number, using type-specific conversion rules. | O(1) | O(1) |
192
- | `useToBigInt<T = unknown>(target: T)` | Converts any value to a bigint, using type-specific conversion rules. | O(1) | O(1) |
193
-
194
- ```typescript
195
- // Utility function usage examples
196
- let numbers: Array<number> = [3, 1, 4, 1, 5];
197
- numbers.sort(useCompare); // [1, 1, 3, 4, 5]
198
-
199
- let randomNum: number = useRandom(42); // Seed-based random number
200
-
201
- let o = {
202
- a: 1,
203
- b: {
204
- c: 2,
205
- d: o
206
- },
207
- c: [1, 3, 5, o],
208
- e: undefined,
209
- f: null
210
- };
211
- useTraverse(o, (value, key): boolean => {
212
- console.log(key, value);
213
- /*
214
- a 1
215
- c 2
216
- 1 3 5
217
- Cyclic references, undefined and null values are not traversed.
218
- */
219
- return true; // Returns true to continue traversing.
220
- });
221
- useTraverse(o, (value, key, path: Array<string | number | symbol>): boolean => {
222
- console.log(key, value, path);
223
- return true; // Returns true to continue traversing.
224
- });
225
-
226
- let toBeResolved: object = {
227
- [Symbol.toPrimitive]: () => 5
228
- };
229
- let resolvedNumber: number = useToNumber(toBeResolved); // 5
230
- let resolvedBigInt: bigint = useToBigInt(toBeResolved); // 5n
231
- ```
232
-
233
- ## Hash Algorithms
234
-
235
- | Function | Description | Time Complexity | Space Complexity |
236
- |--------|-------------|-----------------|------------------|
237
- | `maskOf(type: Type)` | Returns a predefined 64-bit mask value corresponding to a given type string. | O(1) | O(1) |
238
- | `register<T>(type: Type, handler: Handler<T>)` | Registers a custom hash computation handler for a specific type. | O(1) | O(1) |
239
- | `unregister(type: Type)` | Unregisters a custom hash computation handler (only for non-built-in types). | O(1) | O(1) |
240
- | `useHash<T = unknown>(target: T)` | Computes a 64-bit hash value for a single input of any type. For objects, it recursively traverses all properties. | O(1) for primitives, O(n) for objects where n is the total number of enumerable properties | O(1) for primitives, O(d) for objects where d is the maximum recursion depth |
241
- | `useHash(...value: Array<unknown>)` | Computes a 64-bit hash value for an array of values, treating the array as a single composite input. | O(k) where k is the number of elements in the array, plus O(n) for nested object traversal | O(d) where d is the maximum recursion depth for nested objects within the array |
242
-
243
- ## HashMap Class Methods
244
-
245
- | Function | Description | Time Complexity | Space Complexity |
246
- |----------|-------------|-----------------|------------------|
247
- | `clear(): void` | Removes all key-value mappings from this map. | O(n) | O(1) |
248
- | `compute(key: K, remapping: BiFunctional<K, MaybeInvalid<V>, MaybeInvalid<V>>): MaybeInvalid<V>` | Attempts to compute a new mapping for the specified `key` and its current mapped value (or `undefined` if none). The `remapping` function generates the new value. Returns the new value associated with the key, or `undefined` if the mapping was removed. | O(1) avg / O(n) worst | O(1) |
249
- | `computeIfAbsent(key: K, remapping: Supplier<V>): V` | If the specified `key` is not already associated with a value (or is mapped to `undefined`), attempts to compute its value using the `remapping` function and enters it into this map. Returns the current (existing or computed) value associated with the key. | O(1) avg / O(n) worst | O(1) |
250
- | `computeIfPresent(key: K, remapping: BiFunctional<K, V, MaybeInvalid<V>>): MaybeInvalid<V>` | If the value for the specified `key` is present and not `undefined`, attempts to compute a new mapping using the `remapping` function. Returns the new value if the mapping is updated, or `undefined` if the mapping was removed. Returns the original value if the key was not present. | O(1) avg / O(n) worst | O(1) |
251
- | `delete(key: K): boolean` | Removes the mapping for a `key` from this map if it is present. Returns `true` if the map contained the key, otherwise `false`. | O(1) avg / O(n) worst | O(1) |
252
- | `entries(): MapIterator<[K, V]>` | Returns a new iterator object that contains an array of `[key, value]` for each element in this map in insertion order. | O(1) | O(1) |
253
- | `forEach(consumer: BiConsumer<V, K>): void` | Executes the provided `consumer` function once for each key-value pair in this map, in insertion order. | O(n) | O(1) |
254
- | `forEach(consumer: TriConsumer<V, K, Map<K, V>>): void` | Executes the provided `consumer` function (which also receives the map itself) once for each key-value pair in this map, in insertion order. | O(n) | O(1) |
255
- | `get(key: K): MaybeUndefined<V>` | Returns the value associated with the specified `key`, or `undefined` if the map contains no mapping for the key. | O(1) avg / O(n) worst | O(1) |
256
- | `get(key: K, defaultValue: V): V` | Returns the value associated with the specified `key`, or the provided `defaultValue` if the map contains no mapping for the key. | O(1) avg / O(n) worst | O(1) |
257
- | `has(key: K): boolean` | Returns `true` if this map contains a mapping for the specified `key`. | O(1) avg / O(n) worst | O(1) |
258
- | `keys(): MapIterator<K>` | Returns a new iterator object that contains the keys for each element in this map in insertion order. | O(1) | O(1) |
259
- | `replace(key: K, value: V): MaybeInvalid<V>` | Replaces the entry for the specified `key` only if it is currently mapped to some value. Returns the previous value associated with the key, or `undefined` if there was no mapping. | O(1) avg / O(n) worst | O(1) |
260
- | `replace(key: K, oldValue: V, newValue: V): boolean` | Replaces the entry for the specified `key` only if it is currently mapped to the specified `oldValue`. Returns `true` if the value was replaced. | O(1) avg / O(n) worst | O(1) |
261
- | `replaceAll(operator: BiFunctional<K, V, MaybeInvalid<V>>): void` | Replaces each entry's value with the result of invoking the given `operator` on that entry until all entries have been processed or the function throws an exception. Entries are removed if the operator returns an invalid value. | O(n) | O(1) |
262
- | `set(key: K, value: V): this` | Associates the specified `value` with the specified `key` in this map. If the map previously contained a mapping for the key, the old value is replaced. Returns the `HashMap` instance for chaining. | O(1) avg / O(n) worst | O(1) |
263
- | `values(): IterableIterator<V>` | Returns a new iterator object that contains the values for each element in this map in insertion order. | O(1) | O(1) |
264
-
265
- ## AbstractSemanticMap Class Methods
266
-
267
- | Method | Description |
268
- |--------|-------------|
269
- | `clear()` | Removes all key-value pairs from the map. |
270
- | `compute(key: K, remapping: BiFunctional<K, MaybeInvalid<V>, MaybeInvalid<V>>)` | Attempts to compute a mapping for the specified key and its current value, returning the new value. |
271
- | `computeIfAbsent(key: K, remapping: Supplier<V>)` | If the specified key is not associated with a value, attempts to compute its value using the given remapping function. |
272
- | `computeIfPresent(key: K, remapping: BiFunctional<K, V, MaybeInvalid<V>>)` | If the specified key is present, attempts to compute a new mapping given the key and its current value. |
273
- | `delete(key: K)` | Removes the entry for the specified key, returning true if the key existed. |
274
- | `entries()` | Returns a new iterator that yields the key-value pairs for each entry. |
275
- | `forEach(consumer: BiConsumer<V, K>)` | Executes a provided function once for each key-value pair. |
276
- | `forEach(consumer: TriConsumer<V, K, Map<K, V>>)` | Executes a provided function once for each key-value pair, passing the map as a third argument. |
277
- | `get(key: K)` | Returns the value associated with the specified key, or undefined if the key is absent. |
278
- | `get(key: K, defaultValue: V)` | Returns the value associated with the specified key, or the provided default value if the key is absent. |
279
- | `has(key: K)` | Returns a boolean indicating whether the map contains a value for the specified key. |
280
- | `replace(key: K, value: V)` | Replaces the entry for the specified key only if it is currently mapped to a value, returning the previous value. |
281
- | `replace(key: K, oldValue: V, newValue: V)` | Replaces the entry for the specified key only if it is currently mapped to the specified old value, returning a boolean indicating success. |
282
- | `replaceAll(operator: BiFunctional<K, V, MaybeInvalid<V>>)` | Replaces each entry's value with the result of applying the given operator to that entry. |
283
- | `set(key: K, value: V)` | Associates the specified value with the specified key, returning the map. |
284
- | `values()` | Returns a new iterator that yields the values for each entry. |
285
- | `keys()` | Returns a new iterator that yields the keys for each entry. |
286
-
287
- ## HashMap Class Methods
288
-
289
- | Method | Description |
290
- |--------|-------------|
291
- | `HashMap()` | Constructs an empty HashMap with default comparator, threshold (0.75), and capacity (16). |
292
- | `HashMap(comparator: Comparator<K>)` | Constructs an empty HashMap with the specified comparator, default threshold (0.75), and capacity (16). |
293
- | `HashMap(threashold: number, initialCapacity: number)` | Constructs an empty HashMap with default comparator, specified threshold, and initial capacity. |
294
- | `HashMap(comparator: Comparator<K>, threashold: number, capacity: number)` | Constructs an empty HashMap with specified comparator, threshold, and capacity. |
295
- | `clear()` | Removes all key-value pairs from the map. |
296
- | `delete(key: K)` | Removes the entry for the specified key, returning true if the key existed. |
297
- | `entries()` | Returns a new iterator that yields the key-value pairs for each entry. |
298
- | `forEach(consumer: BiConsumer<V, K>)` | Executes a provided function once for each key-value pair. |
299
- | `forEach(consumer: TriConsumer<V, K, Map<K, V>>)` | Executes a provided function once for each key-value pair, passing the map as a third argument. |
300
- | `get(key: K)` | Returns the value associated with the specified key, or undefined if the key is absent. |
301
- | `get(key: K, defaultValue: V)` | Returns the value associated with the specified key, or the provided default value if the key is absent. |
302
- | `has(key: K)` | Returns a boolean indicating whether the map contains a value for the specified key. |
303
- | `replace(key: K, value: V)` | Replaces the entry for the specified key only if it is currently mapped to a value, returning the previous value. |
304
- | `replace(key: K, oldValue: V, newValue: V)` | Replaces the entry for the specified key only if it is currently mapped to the specified old value, returning a boolean indicating success. |
305
- | `replaceAll(operator: BiFunctional<K, V, MaybeInvalid<V>>)` | Replaces each entry's value with the result of applying the given operator to that entry. |
306
- | `set(key: K, value: V)` | Associates the specified value with the specified key, returning the map. |
307
- | `values()` | Returns a new iterator that yields the values for each entry. |
308
- | `keys()` | Returns a new iterator that yields the keys for each entry. |
309
-
310
- ## Optional Factory Methods
311
-
312
- | Method | Description | Time Complexity | Space Complexity |
313
- |------|------|------------|------------|
314
- | `Optional.empty<T>(): Optional<T>` | Create an empty Optional | O(1) | O(1) |
315
- | `Optional.of<T>(value): Optional<T>` | Create an Optional containing a value | O(1) | O(1) |
316
- | `Optional.ofNullable<T>(value): Optional<T>` | Create a potentially empty Optional | O(1) | O(1) |
317
- | `Optional.ofNonNull<T>(value): Optional<T>` | Create a non-null Optional | O(1) | O(1) |
318
- | `useNullable` | Creates an Optional from a nullable value (may be null or undefined). | O(1) | O(1) |
319
- | `useNonNull` | Creates an Optional from a non-null value, throwing if the value is null or undefined. | O(1) | O(1) |
320
-
321
- ```typescript
322
- // Optional usage examples
323
- let empty: Optional<number> = Optional.empty();
324
- let present: Optional<number> = Optional.of(42);
325
- let nullable: Optional<string> = Optional.ofNullable<string>(null);
326
- let nonNull: Optional<string> = Optional.ofNonNull("hello");
327
-
328
- present.ifPresent((value: number): void => console.log(value)); // Outputs 42
329
- console.log(empty.get(100)); // Outputs 100
330
- ```
331
-
332
- ## Optional Class Methods
333
-
334
- | Method | Description | Time Complexity | Space Complexity |
335
- |--------|-------------|-----------------|------------------|
336
- | `filter(predicate: Predicate<T>)` | Returns an Optional containing the value if it passes the predicate test, otherwise returns an empty Optional. | O(1) | O(1) |
337
- | `get()` | Returns the contained value if present, otherwise throws a TypeError. | O(1) | O(1) |
338
- | `get(defaultValue: T)` | Returns the contained value if present, otherwise returns the provided default value. | O(1) | O(1) |
339
- | `ifPresent(action: Consumer<T>)` | Executes the given action with the value if present. | O(1) | O(1) |
340
- | `ifPresent(action: Consumer<T>, elseAction: Runnable)` | Executes the given action with the value if present, otherwise executes the elseAction. | O(1) | O(1) |
341
- | `isEmpty()` | Returns true if the Optional contains no value. | O(1) | O(1) |
342
- | `isPresent()` | Returns true if the Optional contains a value. | O(1) | O(1) |
343
- | `map<R>(mapper: Functional<T, R>)` | Applies a mapping function to the contained value and returns an Optional of the result. Returns an empty Optional if no value is present. | O(1) | O(1) |
344
- | `flat(mapper: Functional<T, Optional<T>>)` | Applies a function that returns an Optional to the contained value and returns the result, otherwise returns an empty Optional. | O(1) | O(1) |
345
- | `flatMap<R>(mapper: Functional<T, Optional<R>>)` | Applies a function that returns an Optional of a different type to the contained value and returns the result, otherwise returns an empty Optional. | O(1) | O(1) |
346
- | `orElse(other: MaybeInvalid<T>)` | Returns the contained value if present, otherwise returns the provided alternative value. | O(1) | O(1) |
347
- | `semantic()` | Returns a Semantic that yields the contained value if present, or an empty Semantic if the value is absent. | O(1) | O(1) |
348
-
349
-
350
- ```typescript
351
- // Filter example
352
- let filtered: Optional<number> = Optional.of(42).filter((value: number) => value > 10);
353
- filtered.ifPresent((value: number) => console.log(value)); // Outputs 42
354
-
355
- // Get example
356
- let get: Optional<number> = Optional.of(42);
357
- console.log(get.get()); // Outputs 42
358
- console.log(get.get(100)); // Outputs 42
359
- Optional.of(null).get(); // Throws a TypeError.
360
- console.log(Optional.of(null).get(100)); // Outputs 100
361
-
362
- // IfPresent example
363
- let ifPresent: Optional<number> = Optional.of(42);
364
- ifPresent.ifPresent((value: number) => console.log(value)); // Outputs 42
365
-
366
- // Map example
367
- let mapped: Optional<string> = Optional.of(42).map((value: number) => value.toString());
368
- mapped.ifPresent((value: string) => console.log(value)); // Outputs "42"
369
-
370
- // FlatMap example
371
- let flatMapped: Optional<number> = Optional.of(42).flatMap((value: number) => Optional.of(value * 2));
372
- flatMapped.ifPresent((value: number) => console.log(value)); // Outputs 84
373
-
374
- // Flat example
375
- let a: Optional<number> = Optional.of({
376
- a: Optional.of(1),
377
- }).flat((value) => value.a);
378
- ```
379
-
380
- ### Collector Factory Methods
381
-
382
- | Method | Description | Time Complexity | Space Complexity |
383
- |--------|-------------|-----------------|------------------|
384
- | `Collector.full<E, A, R>(identity: Supplier<A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a Collector that accumulates all elements from a source without interruption. | O(1) for creation | O(1) |
385
- | `Collector.full<E, A, R>(identity: Supplier<A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a Collector that accumulates all elements from a source without interruption, with index support. | O(1) for creation | O(1) |
386
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: Predicate<E>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a unary predicate. | O(1) for creation | O(1) |
387
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: Predicate<E>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a unary predicate, with index support. | O(1) for creation | O(1) |
388
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: BiPredicate<E, bigint>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a binary predicate. | O(1) for creation | O(1) |
389
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: BiPredicate<E, bigint>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a binary predicate, with index support. | O(1) for creation | O(1) |
390
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: TriPredicate<E, bigint, A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a ternary predicate (element, index, accumulator). | O(1) for creation | O(1) |
391
- | `Collector.shortable<E, A, R>(identity: Supplier<A>, interrupt: TriPredicate<E, bigint, A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a Collector that can stop early based on a ternary predicate, with index support. | O(1) for creation | O(1) |
392
-
393
- ### Collector Class Methods
394
-
395
- | Method | Description | Time Complexity | Space Complexity |
396
- |--------|-------------|-----------------|------------------|
397
- | `collect(generator: Generator<E>)` | Collects elements from a generator function, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(n) where n is the number of processed elements | O(1) or O(n) depending on accumulator/finisher |
398
- | `collect(iterable: Iterable<E>)` | Collects elements from an iterable, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(n) where n is the number of processed elements | O(1) or O(n) depending on accumulator/finisher |
399
- | `collect(semantic: Semantic<E>)` | Collects elements from a semantic, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(n) where n is the number of processed elements | O(1) or O(n) depending on accumulator/finisher |
400
- | `collect(collectable: Collectable<E>)` | Collects elements from a collectable, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(n) where n is the number of processed elements | O(1) or O(n) depending on accumulator/finisher |
401
- | `collect(start: number, end: number)` | Collects a numeric range, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(end-start) | O(1) or O(n) depending on accumulator/finisher |
402
- | `collect(start: bigint, end: bigint)` | Collects a big integer range, applying the accumulator and finisher. Stops early if the interrupt condition returns true. | O(Number(end-start)) | O(1) or O(n) depending on accumulator/finisher |
403
-
404
- ## Collector Factory Functions
405
-
406
- | Method | Description | Time Complexity | Space Complexity |
407
- |--------|-------------|-----------------|------------------|
408
- | `useAnyMatch<E>(predicate: Predicate<E>)` | Creates a collector that checks if any element matches the predicate, short-circuiting when a match is found. | O(1) | O(1) |
409
- | `useAnyMatch<E>(predicate: BiPredicate<E, bigint>)` | Creates a collector that checks if any element matches the indexed predicate, short-circuiting when a match is found. | O(1) | O(1) |
410
- | `useAllMatch<E>(predicate: Predicate<E>)` | Creates a collector that checks if all elements match the predicate, short-circuiting when a non-matching element is found. | O(1) | O(1) |
411
- | `useAllMatch<E>(predicate: BiPredicate<E, bigint>)` | Creates a collector that checks if all elements match the indexed predicate, short-circuiting when a non-matching element is found. | O(1) | O(1) |
412
- | `useCollect<E, A, R>(identity: Supplier<A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a full collector (no early termination) that accumulates elements into a result container. | O(1) | O(1) |
413
- | `useCollect<E, A, R>(identity: Supplier<A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a full collector (no early termination) that accumulates elements with indices into a result container. | O(1) | O(1) |
414
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: Predicate<E>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a unary predicate, accumulating elements into a result container. | O(1) | O(1) |
415
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: Predicate<E>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a unary predicate, accumulating elements with indices into a result container. | O(1) | O(1) |
416
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: BiPredicate<E, bigint>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a binary predicate, accumulating elements into a result container. | O(1) | O(1) |
417
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: BiPredicate<E, bigint>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a binary predicate, accumulating elements with indices into a result container. | O(1) | O(1) |
418
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: TriPredicate<E, bigint, A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a ternary predicate, accumulating elements into a result container. | O(1) | O(1) |
419
- | `useCollect<E, A, R>(identity: Supplier<A>, interrupt: TriPredicate<E, bigint, A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>)` | Creates a short-circuit collector that can stop early based on a ternary predicate, accumulating elements with indices into a result container. | O(1) | O(1) |
420
- | `useCount<E = unknown>()` | Creates a collector that counts the number of elements. | O(1) | O(1) |
421
- | `useError<E = unknown>()` | Creates a collector that accumulates elements into a string, logs an error, and returns the string. | O(1) | O(1) |
422
- | `useError<E = unknown>(accumulator: BiFunctional<string, E, string>)` | Creates a collector that accumulates elements into a string using a custom accumulator, logs an error, and returns the string. | O(1) | O(1) |
423
- | `useError<E = unknown>(accumulator: TriFunctional<string, E, bigint, string>)` | Creates a collector that accumulates elements into a string using a custom indexed accumulator, logs an error, and returns the string. | O(1) | O(1) |
424
- | `useError<E = unknown>(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string)` | Creates a collector that accumulates elements into a string with custom prefix, accumulator, and suffix, logs an error, and returns the string. | O(1) | O(1) |
425
- | `useError<E = unknown>(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string)` | Creates a collector that accumulates elements into a string with custom prefix, indexed accumulator, and suffix, logs an error, and returns the string. | O(1) | O(1) |
426
- | `useFindAt<E>(index: number)` | Creates a collector that finds the element at a specific index, or returns an empty Optional if the index is out of bounds. | O(1) | O(1) |
427
- | `useFindAt<E>(index: bigint)` | Creates a collector that finds the element at a specific bigint index, or returns an empty Optional if the index is out of bounds. | O(1) | O(1) |
428
- | `useFindFirst<E>()` | Creates a collector that finds the first element, short-circuiting when found. | O(1) | O(1) |
429
- | `useFindAny<E>()` | Creates a collector that finds any element (non-deterministic), short-circuiting when found. | O(1) | O(1) |
430
- | `useFindLast<E>()` | Creates a collector that finds the last element. | O(1) | O(1) |
431
- | `useFindMaximum<E>()` | Creates a collector that finds the maximum element using default comparison. | O(1) | O(1) |
432
- | `useFindMaximum<E>(comparator: Comparator<E>)` | Creates a collector that finds the maximum element using a custom comparator. | O(1) | O(1) |
433
- | `useFindMinimum<E>()` | Creates a collector that finds the minimum element using default comparison. | O(1) | O(1) |
434
- | `useFindMinimum<E>(comparator: Comparator<E>)` | Creates a collector that finds the minimum element using a custom comparator. | O(1) | O(1) |
435
- | `useForEach<E>(action: Consumer<E>)` | Creates a collector that performs an action on each element and counts the number of elements processed. | O(1) | O(1) |
436
- | `useForEach<E>(action: BiConsumer<E, bigint>)` | Creates a collector that performs an indexed action on each element and counts the number of elements processed. | O(1) | O(1) |
437
- | `useNoneMatch<E>(predicate: Predicate<E>)` | Creates a collector that checks if no elements match the predicate, short-circuiting when a match is found. | O(1) | O(1) |
438
- | `useNoneMatch<E>(predicate: BiPredicate<E, bigint>)` | Creates a collector that checks if no elements match the indexed predicate, short-circuiting when a match is found. | O(1) | O(1) |
439
- | `useGroup<E, K>(classifier: Functional<E, K>)` | Creates a collector that groups elements by a key, resulting in a Map of keys to arrays of elements. | O(1) | O(1) |
440
- | `useGroup<E, K>(classifier: BiFunctional<E, bigint, K>)` | Creates a collector that groups elements by an indexed key, resulting in a Map of keys to arrays of elements. | O(1) | O(1) |
441
- | `useGroupBy<E, K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>)` | Creates a collector that groups elements by a key and maps each element to a value, resulting in a Map of keys to arrays of values. | O(1) | O(1) |
442
- | `useGroupBy<E, K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, V>)` | Creates a collector that groups elements by an indexed key and maps each element to an indexed value, resulting in a Map of keys to arrays of values. | O(1) | O(1) |
443
- | `useJoin<E = unknown>()` | Creates a collector that joins elements into a string with default formatting. | O(1) | O(1) |
444
- | `useJoin<E = unknown>(delimiter: string)` | Creates a collector that joins elements into a string with a custom delimiter. | O(1) | O(1) |
445
- | `useJoin<E = unknown>(prefix: string, delimiter: string, suffix: string)` | Creates a collector that joins elements into a string with custom prefix, delimiter, and suffix. | O(1) | O(1) |
446
- | `useJoin<E = unknown>(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string)` | Creates a collector that joins elements into a string with custom prefix, accumulator, and suffix. | O(1) | O(1) |
447
- | `useJoin<E = unknown>(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string)` | Creates a collector that joins elements into a string with custom prefix, indexed accumulator, and suffix. | O(1) | O(1) |
448
- | `useLog<E = unknown>()` | Creates a collector that accumulates elements into a string, logs the result, and returns the string. | O(1) | O(1) |
449
- | `useLog<E = unknown>(accumulator: BiFunctional<string, E, string>)` | Creates a collector that accumulates elements into a string using a custom accumulator, logs the result, and returns the string. | O(1) | O(1) |
450
- | `useLog<E = unknown>(accumulator: TriFunctional<string, E, bigint, string>)` | Creates a collector that accumulates elements into a string using a custom indexed accumulator, logs the result, and returns the string. | O(1) | O(1) |
451
- | `useLog<E = unknown>(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string)` | Creates a collector that accumulates elements into a string with custom prefix, accumulator, and suffix, logs the result, and returns the string. | O(1) | O(1) |
452
- | `useLog<E = unknown>(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string)` | Creates a collector that accumulates elements into a string with custom prefix, indexed accumulator, and suffix, logs the result, and returns the string. | O(1) | O(1) |
453
- | `usePartition<E>(count: bigint)` | Creates a collector that partitions elements into a fixed number of arrays. | O(1) | O(1) |
454
- | `usePartitionBy<E>(classifier: Functional<E, bigint>)` | Creates a collector that partitions elements into arrays based on a classifier function. | O(1) | O(1) |
455
- | `usePartitionBy<E>(classifier: BiFunctional<E, bigint, bigint>)` | Creates a collector that partitions elements into arrays based on an indexed classifier function. | O(1) | O(1) |
456
- | `useReduce<E>(accumulator: BiFunctional<E, E, E>)` | Creates a collector that reduces the elements using an associative accumulation function, returning an Optional. | O(1) | O(1) |
457
- | `useReduce<E>(accumulator: TriFunctional<E, E, bigint, E>)` | Creates a collector that reduces the elements using an indexed associative accumulation function, returning an Optional. | O(1) | O(1) |
458
- | `useReduce<E>(identity: E, accumulator: BiFunctional<E, E, E>)` | Creates a collector that reduces the elements using an associative accumulation function and an identity value. | O(1) | O(1) |
459
- | `useReduce<E>(identity: E, accumulator: TriFunctional<E, E, bigint, E>)` | Creates a collector that reduces the elements using an indexed associative accumulation function and an identity value. | O(1) | O(1) |
460
- | `useReduce<E, R>(identity: R, accumulator: BiFunctional<R, E, R>, finisher: Functional<R, R>)` | Creates a collector that reduces the elements into a result container using an identity, accumulator, and finisher. | O(1) | O(1) |
461
- | `useReduce<E, R>(identity: R, accumulator: TriFunctional<R, E, bigint, R>, finisher: Functional<R, R>)` | Creates a collector that reduces the elements into a result container using an identity, indexed accumulator, and finisher. | O(1) | O(1) |
462
- | `useToArray<E>()` | Creates a collector that accumulates elements into an array. | O(1) | O(1) |
463
- | `useToMap<E, K>(keyExtractor: Functional<E, K>)` | Creates a collector that accumulates elements into a Map, using the key extractor and the element itself as the value. | O(1) | O(1) |
464
- | `useToMap<E, K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>)` | Creates a collector that accumulates elements into a Map, using the key and value extractors. | O(1) | O(1) |
465
- | `useToMap<E, K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, V>)` | Creates a collector that accumulates elements into a Map, using indexed key and value extractors. | O(1) | O(1) |
466
- | `useToHashMap<E, K>(keyExtractor: Functional<E, K>)` | Creates a collector that accumulates elements into a HashMap, using the key extractor and the element itself as the value. | O(1) | O(1) |
467
- | `useToHashMap<E, K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>)` | Creates a collector that accumulates elements into a HashMap, using the key and value extractors. | O(1) | O(1) |
468
- | `useToHashMap<E, K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, V>)` | Creates a collector that accumulates elements into a HashMap, using indexed key and value extractors. | O(1) | O(1) |
469
- | `useToSet<E>()` | Creates a collector that accumulates elements into a Set. | O(1) | O(1) |
470
- | `useToHashSet<E>()` | Creates a collector that accumulates elements into a HashSet. | O(1) | O(1) |
471
- | `useWrite<E, S = string>(stream: WritableStream<S>)` | Creates a collector that writes elements to a writable stream. | O(1) | O(1) |
472
- | `useWrite<E, S = string>(stream: WritableStream<S>, accumulator: BiFunctional<WritableStream<S>, E, WritableStream<S>>)` | Creates a collector that writes elements to a writable stream using a custom accumulator. | O(1) | O(1) |
473
- | `useWrite<E, S = string>(stream: WritableStream<S>, accumulator: TriFunctional<WritableStream<S>, E, bigint, WritableStream<S>>)` | Creates a collector that writes elements to a writable stream using a custom indexed accumulator. | O(1) | O(1) |
474
- | `useNumericSummate<E>()` | Creates a collector that sums numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
475
- | `useNumericSummate<E>(mapper: Functional<E, number>)` | Creates a collector that sums numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
476
- | `useBigIntSummate<E>()` | Creates a collector that sums big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
477
- | `useBigIntSummate<E>(mapper: Functional<E, bigint>)` | Creates a collector that sums big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
478
- | `useNumericAverage<E>()` | Creates a collector that calculates the arithmetic mean of numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
479
- | `useNumericAverage<E>(mapper: Functional<E, number>)` | Creates a collector that calculates the arithmetic mean of numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
480
- | `useBigIntAverage<E>()` | Creates a collector that calculates the arithmetic mean of big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
481
- | `useBigIntAverage<E>(mapper: Functional<E, bigint>)` | Creates a collector that calculates the arithmetic mean of big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
482
- | `useFrequency<E>()` | Creates a collector that counts the frequency of each distinct element, returning a Map of elements to their counts. | O(1) for collector creation | O(1) |
483
- | `useNumericMode<E>()` | Creates a collector that finds the mode (most frequent value) of numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
484
- | `useNumericMode<E>(mapper: Functional<E, number>)` | Creates a collector that finds the mode of numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
485
- | `useBigIntMode<E>()` | Creates a collector that finds the mode of big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
486
- | `useBigIntMode<E>(mapper: Functional<E, bigint>)` | Creates a collector that finds the mode of big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
487
- | `useNumericVariance<E>()` | Creates a collector that calculates the population variance of numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
488
- | `useNumericVariance<E>(mapper: Functional<E, number>)` | Creates a collector that calculates the population variance of numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
489
- | `useBigIntVariance<E>()` | Creates a collector that calculates the population variance of big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
490
- | `useBigIntVariance<E>(mapper: Functional<E, bigint>)` | Creates a collector that calculates the population variance of big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
491
- | `useNumericStandardDeviation<E>()` | Creates a collector that calculates the population standard deviation of numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
492
- | `useNumericStandardDeviation<E>(mapper: Functional<E, number>)` | Creates a collector that calculates the population standard deviation of numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
493
- | `useBigIntStandardDeviation<E>()` | Creates a collector that calculates the population standard deviation of big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
494
- | `useBigIntStandardDeviation<E>(mapper: Functional<E, bigint>)` | Creates a collector that calculates the population standard deviation of big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
495
- | `useNumericMedian<E>()` | Creates a collector that calculates the median of numeric values, defaulting to converting elements to numbers. | O(1) for collector creation | O(1) |
496
- | `useNumericMedian<E>(mapper: Functional<E, number>)` | Creates a collector that calculates the median of numeric values after applying a mapping function. | O(1) for collector creation | O(1) |
497
- | `useBigIntMedian<E>()` | Creates a collector that calculates the median of big integer values, defaulting to converting elements to bigints. | O(1) for collector creation | O(1) |
498
- | `useBigIntMedian<E>(mapper: Functional<E, bigint>)` | Creates a collector that calculates the median of big integer values after applying a mapping function. | O(1) for collector creation | O(1) |
499
- | `useToGeneratorFunction<E>()` | Creates a collector that accumulates elements into an array and returns a generator function that yields each element. | O(1) for collector creation | O(1) |
500
- | `useToAsyncGeneratorFunction<E>()` | Creates a collector that accumulates elements into an array and returns an async generator function that yields each element. | O(1) for collector creation | O(1) |
501
-
502
- ```typescript
503
- // Collector conversion examples
504
- let numbers: Semantic<number> = from([3, 1, 4, 1, 5, 9, 2, 6, 5]);
505
-
506
- // Performance first: use unordered collector
507
- let unordered: UnorderedCollectable<number> = from([3, 1, 4, 1, 5, 9, 2, 6, 5])
508
- .filter((n: number): boolean => n > 3)
509
- .toUnoredered();
510
-
511
- // Sorting needed: use ordered collector
512
- let ordered: OrderedCollectable<number> = from([3, 1, 4, 1, 5, 9, 2, 6, 5])
513
- .sorted();
514
-
515
- // Counts the number of elements
516
- let count: Collector<number, number, number> = useCount();
517
- count.collect(from([1,2,3,4,5])); // Counts from a stream
518
- count.collect([1,2,3,4,5]); // Counts from an iterable object
519
-
520
- // Finds the first element
521
- let findFirst: Collector<number, number, number> = useFindFirst();
522
- find.collect(from([1,2,3,4,5])); // Finds the first element
523
- find.collect([1,2,3,4,5]); // Finds the first element
524
-
525
- // Calculates the sum of elements
526
- let summate: Collector<number, number, number> = useSummate();
527
- summate.collect(from([1,2,3,4,5])); // Sums from a stream
528
- summate.collect([1,2,3,4,5]); // Sums from an iterable object
529
-
530
- // Calculates the average of elements
531
- let average: Collector<number, number, number> = useNumericAverage();
532
- average.collect(from([1,2,3,4,5])); // Averages from a stream
533
- average.collect([1,2,3,4,5]); // Averages from an iterable object
534
- ```
535
-
536
- ## Collector Class Methods
537
-
538
- | Method | Description | Time Complexity | Space Complexity |
539
- |--------|-------------|-----------------|------------------|
540
- | `collect(generator: Generator<E>): R` | Collect elements from a generator function | O(n) | O(1) |
541
- | `collect(iterable: Iterable<E>): R` | Collect elements from an iterable object | O(n) | O(1) |
542
- | `collect(semantic: Semantic<E>): R` | Collect elements from a semantic stream | O(n) | O(1) |
543
- | `collect(collectable: Collectable<E>): R` | Collect elements from a collectable stream | O(n) | O(1) |
544
- | `collect(start: number, end: number): R` | Collect elements from a numeric range | O(n) | O(1) |
545
- | `collect(start: bigint, end: bigint): R` | Collect elements from a bigint range | O(n) | O(1) |
546
-
547
- ### Semantic Factory Methods
548
-
549
- | Method | Description | Time Complexity | Space Complexity |
550
- |--------|-------------|-----------------|------------------|
551
- | `useAnimationFrame(period: number)` | Creates a semantic that yields timestamps at each animation frame. | O(1) per animation frame | O(1) |
552
- | `useAnimationFrame(period: number, delay: number)` | Creates a semantic that yields timestamps at each animation frame with a delay before starting. | O(1) per animation frame | O(1) |
553
- | `useAttribute<T extends object>(target: T)` | Creates a semantic that traverses and yields all attributes (key-value pairs) of an object, including nested properties. | O(n) where n is the total number of enumerable properties | O(d) where d is the maximum recursion depth |
554
- | `useBlob(blob: Blob)` | Creates a semantic that reads a Blob in chunks and yields each chunk as a Uint8Array. | O(m/k) where m is blob size, k is chunk size | O(k) where k is chunk size |
555
- | `useBlob(blob: Blob, chunk: bigint)` | Creates a semantic that reads a Blob in chunks of specified size and yields each chunk as a Uint8Array. | O(m/k) where m is blob size, k is chunk size | O(k) where k is chunk size |
556
- | `useDocument<K extends keyof DocumentEventMap>(key: K)` | Creates a semantic that listens to a specified document event and yields event objects. | O(1) per event listener | O(k) where k is number of event listeners |
557
- | `useDocument<K extends keyof DocumentEventMap>(keys: Iterable<K>)` | Creates a semantic that listens to multiple specified document events and yields event objects. | O(1) per event listener | O(k) where k is number of event listeners |
558
- | `useHTMLElement<E extends HTMLElement, K extends keyof HTMLElementEventMap>(element: E, key: K)` | Creates a semantic that listens to a specified event on a single HTML element. | O(1) per event listener | O(1) |
559
- | `useHTMLElement<E extends HTMLElement, K extends keyof HTMLElementEventMap>(element: E, keys: Iterable<K>)` | Creates a semantic that listens to multiple specified events on a single HTML element. | O(m) where m is number of event types | O(m) where m is number of event types |
560
- | `useHTMLElement<E extends HTMLElement, K extends keyof HTMLElementEventMap>(elements: Iterable<E>, key: K)` | Creates a semantic that listens to a specified event on multiple HTML elements. | O(n) where n is number of elements | O(n) where n is number of elements |
561
- | `useHTMLElement<E extends HTMLElement, K extends keyof HTMLElementEventMap>(elements: Iterable<E>, keys: Iterable<K>)` | Creates a semantic that listens to multiple specified events on multiple HTML elements. | O(n×m) where n is number of elements, m is number of event types | O(n×m) where n is number of elements, m is number of event types |
562
- | `useHTMLElement<S extends keyof HTMLElementTagNameMap, K extends keyof HTMLElementEventMap>(selector: S, key: K)` | Creates a semantic that listens to a specified event on elements matching a selector. | O(1) per event listener | O(1) |
563
- | `useHTMLElement<S extends keyof HTMLElementTagNameMap, K extends keyof HTMLElementEventMap>(selector: S, keys: Iterable<K>)` | Creates a semantic that listens to multiple specified events on elements matching a selector. | O(m) where m is number of event types | O(m) where m is number of event types |
564
- | `useHTMLElement<S extends keyof HTMLElementTagNameMap, K extends keyof HTMLElementEventMap>(selectors: Iterable<S>, key: K)` | Creates a semantic that listens to a specified event on elements matching multiple selectors. | O(n) where n is number of selectors | O(n) where n is number of selectors |
565
- | `useHTMLElement<S extends keyof HTMLElementTagNameMap, K extends keyof HTMLElementEventMap>(selectors: Iterable<S>, keys: Iterable<K>)` | Creates a semantic that listens to multiple specified events on elements matching multiple selectors. | O(n×m) where n is number of selectors, m is number of event types | O(n×m) where n is number of selectors, m is number of event types |
566
- | `useEmpty<E>()` | Creates a semantic that immediately completes without yielding any values. | O(1) | O(1) |
567
- | `useFill<E>(element: E, count: bigint)` | Creates a semantic that yields a specified element a given number of times. | O(count) | O(1) |
568
- | `useFill<E>(supplier: Supplier<E>, count: bigint)` | Creates a semantic that yields the result of a supplier function a given number of times. | O(count) | O(1) |
569
- | `useFrom<E>(iterable: Iterable<E>)` | Creates a semantic from an iterable, yielding each element sequentially. | O(n) where n is number of elements | O(1) |
570
- | `useFrom<E>(iterable: AsyncIterable<E>)` | Creates a semantic from an async iterable, yielding each element sequentially. | O(n) where n is number of elements | O(1) |
571
- | `useGenerate<E>(supplier: Supplier<E>, interrupt: Predicate<E>)` | Creates a semantic that continuously yields values from a supplier until a predicate condition is met. | O(∞) in worst case, depends on interrupt | O(1) |
572
- | `useGenerate<E>(supplier: Supplier<E>, interrupt: BiPredicate<E, bigint>)` | Creates a semantic that continuously yields values from a supplier until a bivariate predicate condition is met. | O(∞) in worst case, depends on interrupt | O(1) |
573
- | `useInterval(period: number)` | Creates a semantic that yields incremental numbers at regular intervals. | O(1) per interval | O(1) |
574
- | `useInterval(period: number, delay: number)` | Creates a semantic that yields incremental numbers at regular intervals with an initial delay. | O(1) per interval | O(1) |
575
- | `useIterate<E>(generator: Generator<E>)` | Creates a semantic using a custom generator function that defines the iteration logic. | Depends on the provided generator | Depends on the provided generator |
576
- | `usePromise<T>(promise: Promise<T>)` | Creates a semantic that yields the resolved value of a promise, or fails silently. | O(1) for promise setup | O(1) |
577
- | `useOf<E>(target: E)` | Creates a semantic that yields a single element. | O(1) | O(1) |
578
- | `useOf<E>(target: Iterable<E>)` | Creates a semantic that yields each element from an iterable. | O(n) where n is number of elements | O(1) |
579
- | `useRange<N extends number \| bigint>(start: N, end: N)` | Creates a semantic that yields a sequence of numbers or big integers from start to end with default step. | O((end-start)/step) | O(1) |
580
- | `useRange<N extends number \| bigint>(start: N, end: N, step: N)` | Creates a semantic that yields a sequence of numbers or big integers from start to end with specified step. | O((end-start)/step) | O(1) |
581
- | `useWebSocket(websocket: WebSocket)` | Creates a semantic that listens to all default WebSocket events. | O(1) per event listener | O(k) where k is number of event listeners |
582
- | `useWebSocket<K extends keyof WebSocketEventMap>(websocket: WebSocket, key: K)` | Creates a semantic that listens to a specified WebSocket event. | O(1) per event listener | O(1) |
583
- | `useWebSocket<K extends keyof WebSocketEventMap>(websocket: WebSocket, keys: Iterable<K>)` | Creates a semantic that listens to multiple specified WebSocket events. | O(1) per event listener | O(k) where k is number of event listeners |
584
- | `useWindow<K extends keyof WindowEventMap>(key: K)` | Creates a semantic that listens to a specified window event. | O(1) per event listener | O(1) |
585
- | `useWindow<K extends keyof WindowEventMap>(keys: Iterable<K>)` | Creates a semantic that listens to multiple specified window events. | O(1) per event listener | O(k) where k is number of event listeners |
586
- | `useNullable<T>(target: MaybeInvalid<T>)` | Creates an Optional from a nullable value (may be null or undefined). | O(1) | O(1) |
587
- | `useNonNull<T>(target: T)` | Creates an Optional from a non-null value, throwing if the value is null or undefined. | O(1) | O(1) |
588
-
589
- ```typescript
590
- // Semantic factory method usage examples
591
-
592
- // Create a stream from a timed animation frame
593
- animationFrame(1000)
594
- .toUnordered()
595
- .forEach((frame): void => console.log(frame));
596
-
597
- // Create a stream from a Blob (chunked reading)
598
- blob(someBlob, 1024n)
599
- .toUnordered()
600
- .write(WritableStream)
601
- .then(callback) // Write stream successful
602
- .catch(callback); // Write stream failed
603
-
604
- // Create an empty stream, won't execute until concatenated with other streams
605
- empty<string>()
606
- .toUnordered()
607
- .join(); //[]
608
-
609
- // Create an event stream.
610
- let windowEventStream = event(window, "resize");
611
- let documentEventStream = event(document, "click");
612
- let elementEventStream = event(element, "input");
613
- let multipleWindowEventStream = event(window, ["resize", "scroll"]);
614
- let multipleDocumentEventStream = event(document, ["click", "keydown"]);
615
- let multipleElementEventStream = event([element1, element2], "input");
616
- let multipleMixedEventStream = event([element1, element2, element3], ["resize", "click"]);
617
-
618
- // Create a filled stream
619
- let filledStream = fill("hello", 3); // "hello", "hello", "hello"
620
-
621
- // Create a timed stream with initial 2-second delay and 5-second execution period, implemented based on timer mechanism; may experience time drift due to system scheduling precision limitations.
622
- let intervalStream = interval(5000, 2000);
623
-
624
- // Create a stream from an iterable object
625
- let numberStream = from([1, 2, 3, 4, 5]);
626
- let stringStream = from(new Set(["Alex", "Bob"]));
627
-
628
- // Create a stream from a resolved Promise
629
- let promisedStream: Semantic<Array<number>> = promise(Promise.resolve([1, 2, 3, 4, 5]));
630
-
631
- // Create a range stream
632
- let rangeStream = range(1, 10, 2); // 1, 3, 5, 7, 9
633
-
634
- // WebSocket event stream
635
- let ws = new WebSocket("ws://localhost:8080");
636
- websocket(ws)
637
- .filter((event): boolean => event.type === "message"); // Only listen to message events
638
- .toUnordered() // Generally not ordered for events
639
- .forEach((event): void => receive(event)); // Receive messages
640
- ```
641
-
642
- ## Semantic Class Methods
643
-
644
- | Method | Description | Time Complexity | Space Complexity |
645
- |--------|-------------|-----------------|------------------|
646
- | `constructor(generator: Generator<E>)` | Constructs a new `Semantic<E>` instance from the provided generator function. | O(1) | O(1) |
647
- | `concat(other: Semantic<E>): Semantic<E>` | Creates a new `Semantic<E>` that concatenates the elements of this `Semantic` with those of the provided `Semantic<E>` `other`. | O(1) | O(1) |
648
- | `concat(other: Iterable<E>): Semantic<E>` | Creates a new `Semantic<E>` that concatenates the elements of this `Semantic` with those of the provided `Iterable<E>` `other`. | O(1) | O(1) |
649
- | `distinct(): Semantic<E>` | Creates a new `Semantic<E>` that returns distinct elements from this `Semantic`, using the element itself as the key. | O(1) | O(1) |
650
- | `distinct<K>(keyExtractor: Functional<E, K>): Semantic<E>` | Creates a new `Semantic<E>` that returns distinct elements from this `Semantic`, using the key produced by the `keyExtractor` function. | O(1) | O(1) |
651
- | `distinct<K>(keyExtractor: BiFunctional<E, bigint, K>): Semantic<E>` | Creates a new `Semantic<E>` that returns distinct elements from this `Semantic`, using the key produced by the `keyExtractor` function (which also receives the element's index). | O(1) | O(1) |
652
- | `dropWhile(predicate: Predicate<E>): Semantic<E>` | Creates a new `Semantic<E>` that skips the initial elements of this `Semantic` while the `predicate` returns `true`, then yields the remaining elements. | O(1) | O(1) |
653
- | `dropWhile(predicate: BiPredicate<E, bigint>): Semantic<E>` | Creates a new `Semantic<E>` that skips the initial elements (with their indices) while the `predicate` returns `true`, then yields the remaining elements. | O(1) | O(1) |
654
- | `filter(predicate: Predicate<E>): Semantic<E>` | Creates a new `Semantic<E>` that yields only the elements of this `Semantic` that satisfy the given `predicate`. | O(1) | O(1) |
655
- | `filter(predicate: BiPredicate<E, bigint>): Semantic<E>` | Creates a new `Semantic<E>` that yields only the elements (with their indices) of this `Semantic` that satisfy the given `predicate`. | O(1) | O(1) |
656
- | `flat(mapper: Functional<E, Iterable<E>>): Semantic<E>` | Creates a new `Semantic<E>` that maps each element to an `Iterable<E>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
657
- | `flat(mapper: BiFunctional<E, bigint, Iterable<E>>): Semantic<E>` | Creates a new `Semantic<E>` that maps each element (with its index) to an `Iterable<E>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
658
- | `flat(mapper: Functional<E, Semantic<E>>): Semantic<E>` | Creates a new `Semantic<E>` that maps each element to a `Semantic<E>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
659
- | `flat(mapper: BiFunctional<E, bigint, Semantic<E>>): Semantic<E>` | Creates a new `Semantic<E>` that maps each element (with its index) to a `Semantic<E>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
660
- | `flatMap<R>(mapper: Functional<E, Iterable<R>>): Semantic<R>` | Creates a new `Semantic<R>` that maps each element to an `Iterable<R>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
661
- | `flatMap<R>(mapper: BiFunctional<E, bigint, Iterable<R>>): Semantic<R>` | Creates a new `Semantic<R>` that maps each element (with its index) to an `Iterable<R>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
662
- | `flatMap<R>(mapper: Functional<E, Semantic<R>>): Semantic<R>` | Creates a new `Semantic<R>` that maps each element to a `Semantic<R>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
663
- | `flatMap<R>(mapper: BiFunctional<E, bigint, Semantic<R>>): Semantic<R>` | Creates a new `Semantic<R>` that maps each element (with its index) to a `Semantic<R>` using `mapper`, then flattens and yields the resulting elements. | O(1) | O(1) |
664
- | `limit(n: number): Semantic<E>` | Creates a new `Semantic<E>` that yields at most the first `n` elements (where `n` is a `number`) from this `Semantic`. | O(1) | O(1) |
665
- | `limit(n: bigint): Semantic<E>` | Creates a new `Semantic<E>` that yields at most the first `n` elements (where `n` is a `bigint`) from this `Semantic`. | O(1) | O(1) |
666
- | `map<R>(mapper: Functional<E, R>): Semantic<R>` | Creates a new `Semantic<R>` that yields the results of applying the given `mapper` function to each element of this `Semantic`. | O(1) | O(1) |
667
- | `map<R>(mapper: BiFunctional<E, bigint, R>): Semantic<R>` | Creates a new `Semantic<R>` that yields the results of applying the given `mapper` function (which also receives the index) to each element of this `Semantic`. | O(1) | O(1) |
668
- | `peek(consumer: Consumer<E>): Semantic<E>` | Creates a new `Semantic<E>` that performs the provided `consumer` action on each element as they are consumed from this `Semantic`, then yields the elements unchanged. | O(1) | O(1) |
669
- | `peek(consumer: BiConsumer<E, bigint>): Semantic<E>` | Creates a new `Semantic<E>` that performs the provided `consumer` action (which also receives the index) on each element as they are consumed, then yields the elements unchanged. | O(1) | O(1) |
670
- | `redirect(redirector: BiFunctional<E, bigint, bigint>): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is transformed by the `redirector` function. The elements themselves are unchanged. | O(1) | O(1) |
671
- | `reverse(): Semantic<E>` | Creates a new `Semantic<E>` where the indices of the elements from this `Semantic` are negated (e.g., `0` becomes `-0n`, `1` becomes `-1n`, etc.). | O(1) | O(1) |
672
- | `shuffle(): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is replaced by a hash computed from the element and its original index (using `useHash`). | O(1) | O(1) |
673
- | `shuffle(mapper: BiFunctional<E, bigint, bigint>): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is transformed by the provided `mapper` function (which receives the element and its original index). | O(1) | O(1) |
674
- | `skip(n: number): Semantic<E>` | Creates a new `Semantic<E>` that discards the first `n` elements (where `n` is a `number`) from this `Semantic`, then yields the remaining elements. | O(1) | O(1) |
675
- | `skip(n: bigint): Semantic<E>` | Creates a new `Semantic<E>` that discards the first `n` elements (where `n` is a `bigint`) from this `Semantic`, then yields the remaining elements. | O(1) | O(1) |
676
- | `sorted(): OrderedCollectable<E>` | Creates an `OrderedCollectable<E>` that will yield the elements of this `Semantic` in natural order (using `useCompare` for comparison). | O(1) | O(1) |
677
- | `sorted(comparator: Comparator<E>): OrderedCollectable<E>` | Creates an `OrderedCollectable<E>` that will yield the elements of this `Semantic` sorted according to the provided `comparator` function. | O(1) | O(1) |
678
- | `sub(start: bigint, end: bigint): Semantic<E>` | Creates a new `Semantic<E>` that yields elements from this `Semantic` starting at index `start` (inclusive) up to, but not including, index `end`. | O(1) | O(1) |
679
- | `takeWhile(predicate: Predicate<E>): Semantic<E>` | Creates a new `Semantic<E>` that yields elements from this `Semantic` while the `predicate` returns `true`, then stops. | O(1) | O(1) |
680
- | `takeWhile(predicate: BiPredicate<E, bigint>): Semantic<E>` | Creates a new `Semantic<E>` that yields elements (with their indices) from this `Semantic` while the `predicate` returns `true`, then stops. | O(1) | O(1) |
681
- | `toCollectable(): Collectable<E>` | Creates a `Collectable<E>` from this `Semantic`. This allows terminal collection operations to be performed. | O(1) | O(1) |
682
- | `toCollectable<C extends Collectable<E>>(mapper: Functional<Generator<E>, C>): C` | Creates a `Collectable<E>` from this `Semantic` by applying the provided `mapper` function to its generator. | O(1) | O(1) |
683
- | `toBigintStatistics(): BigIntStatistics<E>` | Creates a `BigIntStatistics<E>` from this `Semantic`, enabling statistical operations on elements as big integers. | O(1) | O(1) |
684
- | `toNumericStatistics(): NumericStatistics<E>` | Creates a `NumericStatistics<E>` from this `Semantic`, enabling statistical operations on elements as numbers. | O(1) | O(1) |
685
- | `toOrdered(): OrderedCollectable<E>` | Creates an `OrderedCollectable<E>` from this `Semantic`. This is an alias for `sorted()`. | O(1) | O(1) |
686
- | `toUnordered(): UnorderedCollectable<E>` | Creates an `UnorderedCollectable<E>` from this `Semantic`. | O(1) | O(1) |
687
- | `toWindow(): WindowCollectable<E>` | Creates a `WindowCollectable<E>` from this `Semantic`. | O(1) | O(1) |
688
- | `translate(offset: number): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is shifted by the specified numeric `offset`. | O(1) | O(1) |
689
- | `translate(offset: bigint): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is shifted by the specified big integer `offset`. | O(1) | O(1) |
690
- | `translate(translator: BiFunctional<E, bigint, bigint>): Semantic<E>` | Creates a new `Semantic<E>` where each element's index is transformed by the provided `translator` function (which receives the element and its original index). | O(1) | O(1) |
691
-
692
- ```typescript
693
- // Semantic operation examples
694
- let result = from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
695
- .filter((n: number): boolean => n % 2 === 0) // Filter even numbers
696
- .map((n: number): number => n * 2) // Multiply by 2
697
- .skip(1) // Skip the first
698
- .limit(3) // Limit to 3 elements
699
- .toUnordered() // Convert to unordered collector
700
- .toArray(); // Convert to array
701
- // Result: [8, 12, 20]
702
-
703
- // Complex operation example
704
- let complexResult = range(1, 100, 1)
705
- .flatMap((n: number): Semantics<number> => from([n, n * 2])) // Map each element to two
706
- .distinct() // Remove duplicates
707
- .shuffle() // Shuffle order
708
- .takeWhile((n: number): boolean => n < 50) // Take elements less than 50
709
- .toOrdered() // Convert to ordered collector
710
- .toArray(); // Convert to array
711
-
712
- // Convert to an ascending sorted array
713
- from([6,4,3,5,2]) // Creates a stream
714
- .sorted() // Sorts the stream in ascending order
715
- .toArray(); // [2, 3, 4, 5, 6]
716
-
717
- // Convert to a descending sorted array
718
- from([6,4,3,5,2]) // Creates a stream
719
- .soted((a: number, b: number): number => b - a) // Sorts the stream in descending order
720
- .toArray(); // [6, 5, 4, 3, 2]
721
-
722
- // Redirect to a reversed array
723
- from([6,4,3,5,2])
724
- .redirect((element, index): bigint => -index) // Redirects to reversed order
725
- .toOrderd() // Keeps the redirected order
726
- .toArray(); // [2, 5, 3, 4, 6]
727
-
728
- // Ignore redirections to reverse array
729
- from([6,4,3,5,2])
730
- .redirect((element: number, index: bigint) => -index) // Redirects to reversed order
731
- .toUnorderd() // Drops the redirected order. This operation will ignore `redirect`, `reverse`, `shuffle` and `translate` operations
732
- .toArray(); // [2, 5, 3, 4, 6]
733
-
734
- // Reverse the stream into an array
735
- from([6, 4, 3, 5, 2])
736
- .reverse() // Reverses the stream
737
- .toOrdered() // Guarantees the reversed order
738
- .toArray(); // [2, 5, 3, 4, 6]
739
-
740
- // Overwrite the shuffled stream into an array
741
- from([6, 4, 3, 5, 2])
742
- .shuffle() // Shuffles the stream
743
- .sorted() // Overwrites the shuffled order. This operation will overwrite `redirect`, `reverse`, `shuffle` and `translate` operations
744
- .toArray(); // [2, 5, 3, 4, 6]
745
-
746
- // Convert to window collector
747
- from([6, 4, 3, 5, 2]).toWindow();
748
-
749
- // Convert to numeric statistics
750
- from([6, 4, 3, 5, 2]).toNumericStatistics();
751
-
752
- // Convert to bigint statistics
753
- from([6n, 4n, 3n, 5n, 2n]).toBigintStatistics();
754
-
755
- // Defines a customized collector to collect data
756
- let customizedCollector = from([1, 2, 3, 4, 5]).toCollectable((generator: Generator<E>) => new CustomizedCollector(generator));
757
- ```
758
-
759
- ## Collectable Collection Methods
760
-
761
- | Method | Description | Time Complexity | Space Complexity |
762
- |--------|-------------|-----------------|------------------|
763
- | `anyMatch(predicate: Predicate<E>): boolean` | Checks if any element in the collectable matches the given `predicate`. Returns `true` if a matching element is found, `false` otherwise. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
764
- | `allMatch(predicate: Predicate<E>): boolean` | Checks if all elements in the collectable match the given `predicate`. Returns `false` upon the first non-matching element. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
765
- | `collect<A, R>(collector: Collector<E, A, R>): R` | Performs a mutable reduction operation on the elements using the provided `Collector`. This is a terminal operation. | O(n) | O(depends on collector) |
766
- | `collect<A, R>(identity: Supplier<A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction using the provided `identity`, `accumulator`, and `finisher` functions. This is a terminal operation. | O(n) | O(1) |
767
- | `collect<A, R>(identity: Supplier<A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction using the provided `identity`, `accumulator` (with index), and `finisher` functions. This is a terminal operation. | O(n) | O(1) |
768
- | `collect<A, R>(identity: Supplier<A>, interruptor: Predicate<E>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate, using `identity`, `accumulator`, and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
769
- | `collect<A, R>(identity: Supplier<A>, interruptor: BiPredicate<E, bigint>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate (with index), using `identity`, `accumulator`, and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
770
- | `collect<A, R>(identity: Supplier<A>, interruptor: TriPredicate<E, bigint, A>, accumulator: BiFunctional<A, E, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate (with index and accumulator), using `identity`, `accumulator`, and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
771
- | `collect<A, R>(identity: Supplier<A>, interruptor: Predicate<E>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate, using `identity`, `accumulator` (with index), and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
772
- | `collect<A, R>(identity: Supplier<A>, interruptor: BiPredicate<E, bigint>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate (with index), using `identity`, `accumulator` (with index), and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
773
- | `collect<A, R>(identity: Supplier<A>, interruptor: TriPredicate<E, bigint, A>, accumulator: TriFunctional<A, E, bigint, A>, finisher: Functional<A, R>): R` | Performs a mutable reduction with a short-circuiting `interruptor` predicate (with index and accumulator), using `identity`, `accumulator` (with index), and `finisher`. This is a terminal operation. | O(n) (average), O(n) (worst) | O(1) |
774
- | `count(): bigint` | Returns the count of elements in the collectable. This is a terminal operation. | O(n) | O(1) |
775
- | `error(): void` | Concatenates elements into a bracketed string (`[...]`) and logs it to `console.error`. This is a terminal operation. | O(n) | O(1) |
776
- | `error(accumulator: BiFunctional<string, E, string>): void` | Builds an error message using the custom `accumulator`, wraps it in brackets, and logs it to `console.error`. This is a terminal operation. | O(n) | O(1) |
777
- | `error(accumulator: TriFunctional<string, E, bigint, string>): void` | Builds an error message using the custom `accumulator` (with index), wraps it in brackets, and logs it to `console.error`. This is a terminal operation. | O(n) | O(1) |
778
- | `error(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string): void` | Builds an error message using the custom `accumulator`, wraps it with `prefix` and `suffix`, and logs it to `console.error`. This is a terminal operation. | O(n) | O(1) |
779
- | `error(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string): void` | Builds an error message using the custom `accumulator` (with index), wraps it with `prefix` and `suffix`, and logs it to `console.error`. This is a terminal operation. | O(n) | O(1) |
780
- | `isEmpty(): boolean` | Returns `true` if the collectable contains no elements, otherwise `false`. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
781
- | `findAny(): Optional<E>` | Returns an `Optional` describing a randomly selected element from the collectable, or an empty `Optional` if it is empty. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
782
- | `findAt(index: number): Optional<E>` | Returns an `Optional` describing the element at the specified numeric `index`. For negative indices, fetches from the end. This is a terminal operation. | O(n) | O(1) |
783
- | `findAt(index: bigint): Optional<E>` | Returns an `Optional` describing the element at the specified big integer `index`. For negative indices, fetches from the end. This is a terminal operation. | O(n) | O(1) |
784
- | `findFirst(): Optional<E>` | Returns an `Optional` describing the first element of the collectable, or an empty `Optional` if it is empty. This is a short-circuiting terminal operation. | O(1) (average), O(n) (worst) | O(1) |
785
- | `findLast(): Optional<E>` | Returns an `Optional` describing the last element of the collectable, or an empty `Optional` if it is empty. This is a terminal operation. | O(n) | O(1) |
786
- | `findMaximum(): Optional<E>` | Returns an `Optional` describing the maximum element according to the default comparator (`useCompare`), or an empty `Optional` if the collectable is empty. This is a terminal operation. | O(n) | O(1) |
787
- | `findMaximum(comparator: Comparator<E>): Optional<E>` | Returns an `Optional` describing the maximum element according to the provided `comparator`, or an empty `Optional` if the collectable is empty. This is a terminal operation. | O(n) | O(1) |
788
- | `findMinimum(): Optional<E>` | Returns an `Optional` describing the minimum element according to the default comparator (`useCompare`), or an empty `Optional` if the collectable is empty. This is a terminal operation. | O(n) | O(1) |
789
- | `findMinimum(comparator: Comparator<E>): Optional<E>` | Returns an `Optional` describing the minimum element according to the provided `comparator`, or an empty `Optional` if the collectable is empty. This is a terminal operation. | O(n) | O(1) |
790
- | `forEach(action: Consumer<E>): void` | Performs the given `action` on each element. This is a terminal operation. | O(n) | O(1) |
791
- | `forEach(action: BiConsumer<E, bigint>): void` | Performs the given `action` (with index) on each element. This is a terminal operation. | O(n) | O(1) |
792
- | `group<K>(classifier: Functional<E, K>): Map<K, Array<E>>` | Groups elements by the key returned by the `classifier` function, returning a `Map<K, E[]>` where each key maps to a list of its corresponding elements. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
793
- | `group<K>(classifier: BiFunctional<E, bigint, K>): Map<K, Array<E>>` | Groups elements (with index) by the key returned by the `classifier` function, returning a `Map<K, E[]>` where each key maps to a list of its corresponding elements. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
794
- | `groupBy<K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>): Map<K, Array<V>>` | Groups elements by keys and values extracted by the provided functions, returning a `Map<K, V[]>` where each key maps to a list of its corresponding values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
795
- | `groupBy<K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, K>): Map<K, Array<V>>` | Groups elements (with index) by keys and values extracted by the provided functions, returning a `Map<K, V[]>` where each key maps to a list of its corresponding values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
796
- | `join(): string` | Concatenates the elements (converted to strings) into a single string, formatted as `[element1,element2,...]`. This is a terminal operation. | O(n) | O(n) |
797
- | `join(delimiter: string): string` | Concatenates the elements into a single string using the specified `delimiter`, formatted within `[...]`. This is a terminal operation. | O(n) | O(n) |
798
- | `join(prefix: string, delimiter: string, suffix: string): string` | Concatenates the elements into a single string using the `delimiter`, and wraps the result with the given `prefix` and `suffix`. This is a terminal operation. | O(n) | O(n) |
799
- | `join(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string): string` | Builds the result string using the custom `accumulator` and wraps it with the given `prefix` and `suffix`. This is a terminal operation. | O(n) | O(n) |
800
- | `join(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string): string` | Builds the result string using the custom `accumulator` (with index) and wraps it with the given `prefix` and `suffix`. This is a terminal operation. | O(n) | O(n) |
801
- | `log(): void` | Logs each element and concatenates them into a bracketed string `[...]`, which is also logged. This is a terminal operation. | O(n) | O(1) |
802
- | `log(accumulator: BiFunctional<string, E, string>): void` | Builds a log message using the custom `accumulator`, wraps it in brackets, and logs it. This is a terminal operation. | O(n) | O(1) |
803
- | `log(accumulator: TriFunctional<string, E, bigint, string>): void` | Builds a log message using the custom `accumulator` (with index), wraps it in brackets, and logs it. This is a terminal operation. | O(n) | O(1) |
804
- | `log(prefix: string, accumulator: BiFunctional<string, E, string>, suffix: string): void` | Builds a log message using the custom `accumulator`, wraps it with `prefix` and `suffix`, and logs it. This is a terminal operation. | O(n) | O(1) |
805
- | `log(prefix: string, accumulator: TriFunctional<string, E, bigint, string>, suffix: string): void` | Builds a log message using the custom `accumulator` (with index), wraps it with `prefix` and `suffix`, and logs it. This is a terminal operation. | O(n) | O(1) |
806
- | `nonMatch(predicate: Predicate<E>): boolean` | Returns `true` if no elements in the collectable match the given `predicate`, otherwise `false`. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
807
- | `nonMatch(predicate: BiPredicate<E, bigint>): boolean` | Returns `true` if no elements (with index) in the collectable match the given `predicate`, otherwise `false`. This is a short-circuiting terminal operation. | O(n) (average), O(n) (worst) | O(1) |
808
- | `partition(count: bigint): Array<Array<E>>` | Partitions elements into a fixed number (`count`) of sub-arrays, distributing elements in a round-robin fashion. Returns an `Array<Array<E>>`. This is a terminal operation. | O(n) | O(k) |
809
- | `partitionBy(classifier: Functional<E, bigint>): Array<Array<E>>` | Partitions elements into sub-arrays based on the index returned by the `classifier` function. Returns an `Array<Array<E>>`. This is a terminal operation. | O(n) | O(k) |
810
- | `partitionBy(classifier: BiFunctional<E, bigint, bigint>): Array<Array<E>>` | Partitions elements (with index) into sub-arrays based on the index returned by the `classifier` function. Returns an `Array<Array<E>>`. This is a terminal operation. | O(n) | O(k) |
811
- | `reduce(accumulator: BiFunctional<E, E, E>): Optional<E>` | Performs a reduction on the elements using the associative `accumulator` function, returning an `Optional<E>`. This is a terminal operation. | O(n) | O(1) |
812
- | `reduce(accumulator: TriFunctional<E, E, bigint, E>): Optional<E>` | Performs a reduction on the elements using the associative `accumulator` function (with index), returning an `Optional<E>`. This is a terminal operation. | O(n) | O(1) |
813
- | `reduce(identity: E, accumulator: BiFunctional<E, E, E>): E` | Performs a reduction on the elements using the provided `identity` and `accumulator` function, returning the reduced value. This is a terminal operation. | O(n) | O(1) |
814
- | `reduce(identity: E, accumulator: TriFunctional<E, E, bigint, E>): E` | Performs a reduction on the elements using the provided `identity` and `accumulator` function (with index), returning the reduced value. This is a terminal operation. | O(n) | O(1) |
815
- | `reduce<R>(identity: R, accumulator: BiFunctional<R, E, R>, finisher: Functional<R, R>): R` | Performs a reduction on the elements to type `R` using the provided `identity`, `accumulator`, and `finisher` functions. This is a terminal operation. | O(n) | O(1) |
816
- | `reduce<R>(identity: R, accumulator: TriFunctional<R, E, bigint, R>, finisher: Functional<R, R>): R` | Performs a reduction on the elements (with index) to type `R` using the provided `identity`, `accumulator` (with index), and `finisher` functions. This is a terminal operation. | O(n) | O(1) |
817
- | `semantic(): Semantic<E>` | Returns a `Semantic<E>` view of this collectable. | O(1) | O(1) |
818
- | `source(): Generator<E>` | (Abstract) Returns the underlying generator function. | O(1) | O(1) |
819
- | `toArray(): Array<E>` | Accumulates the elements into an array. This is a terminal operation. | O(n) | O(n) |
820
- | `toMap<K, V>(keyExtractor: Functional<E, K>): Map<K, V>` | Accumulates elements into a `Map<K, V>` using the `keyExtractor` to determine keys and elements as values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
821
- | `toMap<K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>): Map<K, V>` | Accumulates elements into a `Map<K, V>` using the provided extractor functions for keys and values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
822
- | `toMap<K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, V>): Map<K, V>` | Accumulates elements (with index) into a `Map<K, V>` using the provided extractor functions for keys and values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
823
- | `toHashMap<K, V>(keyExtractor: Functional<E, K>): HashMap<K, V>` | Accumulates elements into a `HashMap<K, V>` using the `keyExtractor` to determine keys and elements as values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
824
- | `toHashMap<K, V>(keyExtractor: Functional<E, K>, valueExtractor: Functional<E, V>): HashMap<K, V>` | Accumulates elements into a `HashMap<K, V>` using the provided extractor functions for keys and values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
825
- | `toHashMap<K, V>(keyExtractor: BiFunctional<E, bigint, K>, valueExtractor: BiFunctional<E, bigint, V>): HashMap<K, V>` | Accumulates elements (with index) into a `HashMap<K, V>` using the provided extractor functions for keys and values. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(k) |
826
- | `toSet(): Set<E>` | Accumulates distinct elements into a `Set<E>`. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(n) |
827
- | `toHashSet(): HashSet<E>` | Accumulates distinct elements into a `HashSet<E>`. This is a terminal operation. | O(n) (average), O(n²) (worst) | O(n) |
828
- | `write<S = string>(stream: WritableStream<S>): Promise<WritableStream<S>>` | Writes each element (converted to string) to the provided `WritableStream<S>`. This is a terminal operation. | O(n) | O(1) |
829
- | `write<S = string>(stream: WritableStream<S>, accumulator: BiFunctional<WritableStream<S>, E, WritableStream<S>>): Promise<WritableStream<S>>` | Writes elements to the provided `WritableStream<S>` using the custom `accumulator`. This is a terminal operation. | O(n) | O(1) |
830
- | `write<S = string>(stream: WritableStream<S>, accumulator: TriFunctional<WritableStream<S>, E, bigint, WritableStream<S>>): Promise<WritableStream<S>>` | Writes elements (with index) to the provided `WritableStream<S>` using the custom `accumulator`. This is a terminal operation. | O(n) | O(1) |
831
-
832
- ```typescript
833
- // Collectable operation examples
834
- let data = from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
835
- .filter((n: number): boolean => n % 2 === 0)
836
- .toOrdered();
837
-
838
- // Match checks
839
- console.log(data.anyMatch((n: number): boolean => n > 5)); // true
840
- console.log(data.allMatch((n: number): boolean => n < 20)); // true
841
-
842
- // Find operations
843
- data.findFirst().ifPresent((n: number): void => console.log(n)); // 2
844
- data.findAny().ifPresent((n: number): void => console.log(n)); // Any element
845
-
846
- // Grouping operations
847
- let grouped = data.groupBy(
848
- (n: number): string => n > 5 ? "large" : "small",
849
- (n: number): number => n * 2
850
- );
851
- // {small: [4, 8], large: [12, 16, 20]}
852
-
853
- // Reduction operations
854
- let sum = data.reduce(0, (accumulator: number, n: number): number => accumulator + n); // 30
855
-
856
- // Output operations
857
- data.join(", "); // "[2, 4, 6, 8, 10]"
858
- ```
859
-
860
- ## Unordered Collectable Methods
861
-
862
- | Method | Description | Time Complexity | Space Complexity |
863
- |--------|-------------|-----------------|------------------|
864
- | `constructor(generator: Generator<E>)` | Creates unordered collectable | O(1) | O(1) |
865
- | `source(): Generator<E>` | Returns generator source | O(1) | O(1) |
866
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
867
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
868
-
869
- ## Ordered Collectable Methods
870
-
871
- | Method | Description | Time Complexity | Space Complexity |
872
- |--------|-------------|-----------------|------------------|
873
- | `constructor(generator: Generator<E>)` | Creates ordered collectable | O(n log n) | O(n) |
874
- | `constructor(generator: Generator<E>, comparator: Comparator<E>)` | Creates ordered collectable with comparator | O(n log n) | O(n) |
875
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
876
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
877
- | `source(): Generator<E>` | Returns indexed generator source | O(1) | O(1) |
878
- | `isEmpty(): boolean` | Returns true if buffer is empty | O(1) | O(1) |
879
-
880
- ## Statistical Analysis Methods
881
-
882
- ### Statisttics Methods
883
-
884
- | Method | Description | Time Complexity | Space Complexity |
885
- |--------|-------------|-----------------|------------------|
886
- | `constructor(generator: Generator<E>)` | Creates a statistics instance | O(n log n) | O(n) |
887
- | `constructor(generator: Generator<E>, comparator: Comparator<E>)` | Creates a statistics instance with comparator | O(n log n) | O(n) |
888
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
889
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
890
- | `count(): bigint` | Returns the number of elements | O(1) | O(1) |
891
- | `average(): D` | Returns the average (arithmetic mean) | O(n) | O(1) |
892
- | `average(mapper: Functional<E, D>): D` | Returns the average of mapped values | O(n) | O(1) |
893
- | `range(): D` | Returns the range (max-min) | O(1) | O(1) |
894
- | `range(mapper: Functional<E, D>): D` | Returns the range of mapped values | O(1) | O(1) |
895
- | `variance(): D` | Returns the variance | O(n) | O(1) |
896
- | `variance(mapper: Functional<E, D>): D` | Returns the variance of mapped values | O(n) | O(1) |
897
- | `standardDeviation(): D` | Returns the standard deviation | O(n) | O(1) |
898
- | `standardDeviation(mapper: Functional<E, D>): D` | Returns the standard deviation of mapped values | O(n) | O(1) |
899
- | `mean(): D` | Returns the mean (same as average) | O(n) | O(1) |
900
- | `mean(mapper: Functional<E, D>): D` | Returns the mean of mapped values | O(n) | O(1) |
901
- | `median(): D` | Returns the median | O(n) | O(n) |
902
- | `median(mapper: Functional<E, D>): D` | Returns the median of mapped values | O(n) | O(n) |
903
- | `mode(): D` | Returns the mode | O(n) | O(n) |
904
- | `mode(mapper: Functional<E, D>): D` | Returns the mode of mapped values | O(n) | O(n) |
905
- | `frequency(): Map<E, bigint>` | Returns the frequency distribution | O(n) | O(n) |
906
- | `summate(): D` | Returns the sum of elements | O(n) | O(1) |
907
- | `summate(mapper: Functional<E, D>): D` | Returns the sum of mapped values | O(n) | O(1) |
908
- | `quantile(quantile: number): D` | Returns the specified quantile | O(1) | O(1) |
909
- | `quantile(quantile: number, mapper: Functional<E, D>): D` | Returns the quantile of mapped values | O(1) | O(1) |
910
- | `interquartileRange(): D` | Returns the interquartile range (IQR) | O(1) | O(1) |
911
- | `interquartileRange(mapper: Functional<E, D>): D` | Returns the IQR of mapped values | O(1) | O(1) |
912
- | `skewness(): D` | Returns the skewness measure | O(n) | O(1) |
913
- | `skewness(mapper: Functional<E, D>): D` | Returns the skewness of mapped values | O(n) | O(1) |
914
- | `kurtosis(): D` | Returns the kurtosis measure | O(n) | O(1) |
915
- | `kurtosis(mapper: Functional<E, D>): D` | Returns the kurtosis of mapped values | O(n) | O(1) |
916
-
917
-
918
- ### NumericStatistics Methods
919
-
920
- | Method | Description | Time Complexity | Space Complexity |
921
- |--------|-------------|-----------------|------------------|
922
- | `constructor(generator: Generator<E>)` | Creates a numeric statistics instance | O(n log n) | O(n) |
923
- | `constructor(generator: Generator<E>, comparator: Comparator<E>)` | Creates a numeric statistics instance with comparator | O(n log n) | O(n) |
924
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
925
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
926
- | `count(): bigint` | Returns the number of elements | O(1) | O(1) |
927
- | `average(): number` | Returns the numeric average | O(n) | O(1) |
928
- | `average(mapper: Functional<E, number>): number` | Returns the average of mapped numeric values | O(n) | O(1) |
929
- | `range(): number` | Returns the numeric range | O(1) | O(1) |
930
- | `range(mapper: Functional<E, number>): number` | Returns the range of mapped numeric values | O(1) | O(1) |
931
- | `variance(): number` | Returns the numeric variance | O(n) | O(1) |
932
- | `variance(mapper: Functional<E, number>): number` | Returns the variance of mapped numeric values | O(n) | O(1) |
933
- | `standardDeviation(): number` | Returns the numeric standard deviation | O(n) | O(1) |
934
- | `standardDeviation(mapper: Functional<E, number>): number` | Returns the standard deviation of mapped numeric values | O(n) | O(1) |
935
- | `mean(): number` | Returns the numeric mean (same as average) | O(n) | O(1) |
936
- | `mean(mapper: Functional<E, number>): number` | Returns the mean of mapped numeric values | O(n) | O(1) |
937
- | `median(): number` | Returns the numeric median | O(n) | O(n) |
938
- | `median(mapper: Functional<E, number>): number` | Returns the median of mapped numeric values | O(n) | O(n) |
939
- | `mode(): number` | Returns the numeric mode | O(n) | O(n) |
940
- | `mode(mapper: Functional<E, number>): number` | Returns the mode of mapped numeric values | O(n) | O(n) |
941
- | `frequency(): Map<E, bigint>` | Returns the frequency distribution | O(n) | O(n) |
942
- | `summate(): number` | Returns the numeric sum | O(n) | O(1) |
943
- | `summate(mapper: Functional<E, number>): number` | Returns the sum of mapped numeric values | O(n) | O(1) |
944
- | `quantile(quantile: number): number` | Returns the specified numeric quantile | O(1) | O(1) |
945
- | `quantile(quantile: number, mapper: Functional<E, number>): number` | Returns the quantile of mapped numeric values | O(1) | O(1) |
946
- | `interquartileRange(): number` | Returns the numeric interquartile range | O(1) | O(1) |
947
- | `interquartileRange(mapper: Functional<E, number>): number` | Returns the IQR of mapped numeric values | O(1) | O(1) |
948
- | `skewness(): number` | Returns the numeric skewness | O(n) | O(1) |
949
- | `skewness(mapper: Functional<E, number>): number` | Returns the skewness of mapped numeric values | O(n) | O(1) |
950
- | `kurtosis(): number` | Returns the numeric kurtosis | O(n) | O(1) |
951
- | `kurtosis(mapper: Functional<E, number>): number` | Returns the kurtosis of mapped numeric values | O(n) | O(1) |
952
-
953
- ```typescript
954
- // Statistical analysis examples
955
- let numbers = from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
956
- .toNumericStatistics();
957
-
958
- console.log("Mean:", numbers.mean()); // 5.5
959
- console.log("Median:", numbers.median()); // 5.5
960
- console.log("Standard deviation:", numbers.standardDeviation()); // ~2.87
961
- console.log("Sum:", numbers.summate()); // 55
962
-
963
- // Statistical analysis using mappers
964
- let objects = from([
965
- { value: 10 },
966
- { value: 20 },
967
- { value: 30 }
968
- ]).toNumericStatistics();
969
-
970
- console.log("Mapped mean:", objects.mean(obj => obj.value)); // 20
971
- ```
972
-
973
- ### BigintStatistics Methods
974
-
975
- | Method | Description | Time Complexity | Space Complexity |
976
- |--------|-------------|-----------------|------------------|
977
- | `constructor(generator: Generator<E>)` | Creates a bigint statistics instance | O(n log n) | O(n) |
978
- | `constructor(generator: Generator<E>, comparator: Comparator<E>)` | Creates a bigint statistics instance with comparator | O(n log n) | O(n) |
979
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
980
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
981
- | `count(): bigint` | Returns the number of elements | O(1) | O(1) |
982
- | `average(): bigint` | Returns the bigint average | O(n) | O(1) |
983
- | `average(mapper: Functional<E, bigint>): bigint` | Returns the average of mapped bigint values | O(n) | O(1) |
984
- | `range(): bigint` | Returns the bigint range | O(1) | O(1) |
985
- | `range(mapper: Functional<E, bigint>): bigint` | Returns the range of mapped bigint values | O(1) | O(1) |
986
- | `variance(): bigint` | Returns the bigint variance | O(n) | O(1) |
987
- | `variance(mapper: Functional<E, bigint>): bigint` | Returns the variance of mapped bigint values | O(n) | O(1) |
988
- | `standardDeviation(): bigint` | Returns the bigint standard deviation | O(n) | O(1) |
989
- | `standardDeviation(mapper: Functional<E, bigint>): bigint` | Returns the standard deviation of mapped bigint values | O(n) | O(1) |
990
- | `mean(): bigint` | Returns the bigint mean (same as average) | O(n) | O(1) |
991
- | `mean(mapper: Functional<E, bigint>): bigint` | Returns the mean of mapped bigint values | O(n) | O(1) |
992
- | `median(): bigint` | Returns the bigint median | O(n) | O(n) |
993
- | `median(mapper: Functional<E, bigint>): bigint` | Returns the median of mapped bigint values | O(n) | O(n) |
994
- | `mode(): bigint` | Returns the bigint mode | O(n) | O(n) |
995
- | `mode(mapper: Functional<E, bigint>): bigint` | Returns the mode of mapped bigint values | O(n) | O(n) |
996
- | `frequency(): Map<E, bigint>` | Returns the frequency distribution | O(n) | O(n) |
997
- | `summate(): bigint` | Returns the bigint sum | O(n) | O(1) |
998
- | `summate(mapper: Functional<E, bigint>): bigint` | Returns the sum of mapped bigint values | O(n) | O(1) |
999
- | `quantile(quantile: number): bigint` | Returns the specified bigint quantile | O(1) | O(1) |
1000
- | `quantile(quantile: number, mapper: Functional<E, bigint>): bigint` | Returns the quantile of mapped bigint values | O(1) | O(1) |
1001
- | `interquartileRange(): bigint` | Returns the bigint interquartile range | O(1) | O(1) |
1002
- | `interquartileRange(mapper: Functional<E, bigint>): bigint` | Returns the IQR of mapped bigint values | O(1) | O(1) |
1003
- | `skewness(): bigint` | Returns the bigint skewness | O(n) | O(1) |
1004
- | `skewness(mapper: Functional<E, bigint>): bigint` | Returns the skewness of mapped bigint values | O(n) | O(1) |
1005
- | `kurtosis(): bigint` | Returns the bigint kurtosis | O(n) | O(1) |
1006
- | `kurtosis(mapper: Functional<E, bigint>): bigint` | Returns the kurtosis of mapped bigint values | O(n) | O(1) |
1007
-
1008
- ### Window Collectable Methods
1009
-
1010
- | Method | Description | Time Complexity | Space Complexity |
1011
- |--------|-------------|-----------------|------------------|
1012
- | `constructor(generator: Generator<E>)` | Creates a window collectable instance | O(n log n) | O(n) |
1013
- | `constructor(generator: Generator<E>, comparator: Comparator<E>)` | Creates a window collectable with comparator | O(n log n) | O(n) |
1014
- | `[Symbol.iterator](): Generator<E, void, undefined>` | Returns iterator | O(n) | O(1) |
1015
- | `[Symbol.asyncIterator](): AsyncGenerator<E, void, undefined>` | Returns async iterator | O(n) | O(1) |
1016
- | `slide(size: bigint): Semantic<Semantic<E>>` | Creates sliding windows of elements with 1 step | O(m × n) | O(m × n) |
1017
- | `slide(size: bigint, step: bigint): Semantic<Semantic<E>>` | Creates sliding windows of elements | O(m × n) | O(m × n) |
1018
- | `tumble(size: bigint): Semantic<Semantic<E>>` | Creates tumbling windows of elements | O(k × n) | O(k × n) |
1019
-
1020
- ## Performance Selection Guide
1021
-
1022
- ### Choose Unordered Collector (Performance First)
1023
- ```typescript
1024
- // When order guarantee is not needed, use unordered collector for best performance
1025
- let highPerformance = data
1026
- .filter(predicate)
1027
- .map(mapper)
1028
- .toUnoredered(); // Best performance
1029
- ```
1030
-
1031
- ### Choose Ordered Collector (Order Required)
1032
- ```typescript
1033
- // When element order needs to be maintained, use ordered collector
1034
- let ordered = data.sorted(comparator);
1035
- ```
1036
-
1037
- ### Choose Window Collector (Window Operations)
1038
- ```typescript
1039
- // When window operations are needed
1040
- let window: WindowCollectable<number> = data
1041
- .toWindow()
1042
- .slide(5n, 2n); // Sliding window
1043
- ```
1044
-
1045
- ### Choose Statistical Analysis (Numerical Calculations)
1046
- ```typescript
1047
- // When statistical analysis is needed
1048
- let statistics: NumericStatistics<number> = data
1049
- .toNumericStatistics(); // Numerical statistics
1050
-
1051
- let bigIntStatistics: BigintStatistics<bigint> = data
1052
- .toBigintStatistics(); // Big integer statistics
1053
- ```
1054
-
1055
- [GitHub](https://github.com/eloyhere/semantic-typescript)
1056
- [NPMJS](https://www.npmjs.com/package/semantic-typescript)
1057
-
1058
- ## Important Notes
1059
-
1060
- 1. **Impact of Sorting Operations**: In ordered collectors, the `sorted()` operation overrides the effects of `redirect`, `translate`, `shuffle`, `reverse`
1061
- 2. **Performance Considerations**: If order guarantee is not needed, prioritise using `toUnoredered()` for better performance
1062
- 3. **Memory Usage**: Sorting operations require O(n) additional space
1063
- 4. **Real-time Data**: Semantic streams are suitable for processing real-time data and support asynchronous data sources
1064
-
1065
- This library provides TypeScript developers with powerful and flexible streaming capabilities, combining the benefits of functional programming with type safety guarantees.
1066
-
1
+ # **Semantic-TypeScript**
2
+ **Flow, Indexed.** Your data, under precise control.
3
+
4
+ ---
5
+
6
+ ### Overview
7
+
8
+ Semantic-TypeScript marks a significant leap forward in stream processing technology, **synthesising** the most effective concepts from JavaScript `GeneratorFunction`, Java Streams, and MySQL-style indexing. Its core philosophy is both simple and powerful: construct exceptionally efficient data-processing pipelines through intelligent indexing, not through brute-force iteration.
9
+
10
+ Where conventional libraries impose synchronous loops or unwieldy promise chains, Semantic-TypeScript delivers a **fully asynchronous**, functionally pure, and rigorously type-safe experience, designed for the demands of modern front-end development.
11
+
12
+ In its elegant model, data only reaches the consumer when the upstream pipeline explicitly invokes the `accept` (and optionally `interrupt`) callbacks. You have complete control over the timing—exactly when it is needed.
13
+
14
+ ---
15
+
16
+ ### Why Developers Prefer It
17
+
18
+ - **Zero-Boilerplate Indexing** — every element carries its natural or bespoke index.
19
+ - **Pure Functional Style** with full TypeScript inference.
20
+ - **Leak-Proof Event Streams** — `useWindow`, `useDocument`, `useHTMLElement`, and `useWebSocket` are built with safety in mind. You define the boundary—using `limit(n)`, `sub(start, end)`, or `takeWhile(predicate)`—and the library manages the cleanup. No lingering listeners, no memory leaks.
21
+ - **Built-in Statistics** — comprehensive numeric and bigint analytics including averages, medians, modes, variance, skewness, and kurtosis.
22
+ - **Predictable Performance** — choose between ordered or unordered collectors based on your requirements.
23
+ - **Memory-Efficient** — streams are evaluated lazily, alleviating memory concerns.
24
+ - **No Undefined Behaviour** TypeScript guarantees type safety and nullability. Input data remains unmodified unless explicitly altered within your callback functions.
25
+
26
+ ---
27
+
28
+ ### Installation
29
+
30
+ ```bash
31
+ npm install semantic-typescript
32
+ ```
33
+ or
34
+ ```bash
35
+ yarn add semantic-typescript
36
+ ```
37
+
38
+ ---
39
+
40
+ ### Quick Start
41
+
42
+ ```typescript
43
+ import { useOf, useFrom, useRange, useWindow, useHTMLElement, useWebSocket, useText, useStringify } from "semantic-typescript";
44
+
45
+ // Numeric statistics
46
+ let summate: number = useOf(10, 20, 30, 40)
47
+ .map((n: number): number => n * 2)
48
+ .toNumericStatistics() // Required before terminal operation
49
+ .summate(); // 200
50
+
51
+ // Bigint statistics
52
+ let summate: bigint = useOf(10n, 20n, 30n, 40n)
53
+ .map((n: bigint): bigint => n * 2)
54
+ .toBigIntStatistics() // Required before terminal operation
55
+ .summate(); // 200n
56
+
57
+ // Reverse a stream by index
58
+ useFrom([1, 2, 3, 4, 5])
59
+ .redirect((element: E, index: bigint): bigint => -index) // Negative index for reversal
60
+ .toOrdered() // Call toOrdered() to preserve index order
61
+ .toArray(); // [5, 4, 3, 2, 1]
62
+
63
+ // Shuffle a stream
64
+ useFrom([1, 2, 3, 4, 5])
65
+ .shuffle()
66
+ .toOrdered()
67
+ .toArray(); // e.g., [2, 5, 1, 4, 3]
68
+
69
+ // Translate elements within a stream
70
+ useFrom([1, 2, 3, 4, 5])
71
+ .translate(2) // Shift elements right by 2 positions
72
+ .toOrdered()
73
+ .toArray(); // [4, 5, 1, 2, 3]
74
+
75
+ useFrom([1, 2, 3, 4, 5])
76
+ .translate(-2) // Shift elements left by 2 positions
77
+ .toOrdered()
78
+ .toArray(); // [3, 4, 5, 1, 2]
79
+
80
+ // Infinite range with early termination
81
+ useRange(0n, 1_000_000n)
82
+ .filter(n => n % 17n === 0n)
83
+ .limit(10n) // Stop after 10 elements
84
+ .toUnordered()
85
+ .toArray();
86
+
87
+ // Real-time window resize (stops automatically after 5 events)
88
+ useWindow("resize")
89
+ .limit(5n) // Crucial for event streams
90
+ .toUnordered()
91
+ .forEach((ev, idx) => console.log(`Resize #${idx}`));
92
+
93
+ // Listen to an HTML element
94
+ // <input id="input" type="text"/>
95
+ useHTMLElement("#input", "change")
96
+ .limit(1)
97
+ .toUnordered()
98
+ .forEach((event: Event) => submit(event));
99
+
100
+ // Listen to multiple elements and events
101
+ useHTMLElement("input", ["change", "keyup"])
102
+ .takeWhile((event: Event): boolean => validate(event))
103
+ .toUnordered()
104
+ .forEach((event: Event) => submit(event));
105
+
106
+ // Listen to a WebSocket
107
+ let webSocket = new WebSocket("ws://localhost:8080");
108
+ webSocket.addEventListener("close", (): void => {
109
+ webSocket.close(); // Manage the WebSocket lifecycle manually
110
+ });
111
+ useWebSocket(webSocket, "message")
112
+ .limit(1)
113
+ .toUnordered()
114
+ .forEach((message: MessageEvent) => console.log(message.data));
115
+
116
+ // Iterate over a string by code point
117
+ useText("My emotion now is: 😊, and semantic is 👍")
118
+ .toUnordered()
119
+ .log(); // Outputs the string
120
+
121
+ // Safely stringify an object with circular references
122
+ let o = {
123
+ a: 1,
124
+ b: "text",
125
+ c: [o.a, o.b, o.c] // Circular reference
126
+ };
127
+ // let text: string = JSON.stringify(o); // Throws an error
128
+ let text: string = useStringify(o); // Safely yields `{a: 1, b: "text", c: []}`
129
+ ```
130
+
131
+ ---
132
+
133
+ ### Core Concepts
134
+
135
+ | Concept | Purpose | When to Use |
136
+ | :--- | :--- | :--- |
137
+ | `AsynchronousSemantic` | Core builder for asynchronous streams, events, and lazy pipelines. | Real-time events, WebSockets, DOM listeners, long-running or infinite streams. |
138
+ | `SynchronousSemantic` | Builder for synchronous, in-memory, or loop-based streams. | Static data, ranges, immediate iteration. |
139
+ | `toUnordered()` | Fastest terminal collector (Map-based indexing). | Performance-critical paths (O(n) time & space, no sorting). |
140
+ | `toOrdered()` | Sorted, index-stable collector. | When stable ordering or indexed access is required. |
141
+ | `toNumericStatistics()` | Rich numeric statistical analysis (mean, median, variance, skewness, kurtosis, etc.). | Data analytics and statistical computations. |
142
+ | `toBigIntStatistics()` | Rich bigint statistical analysis. | Data analytics and statistical computations for large integers. |
143
+ | `toWindow()` | Sliding and tumbling window support. | Time-series processing, batching, and windowed operations. |
144
+
145
+ ---
146
+
147
+ **Important Usage Rules**
148
+
149
+ 1. **Event streams** (`useWindow`, `useDocument`, `useHTMLElement`, `useWebSocket`, …) return an `AsynchronousSemantic`.
150
+ You **must** call `.limit(n)`, `.sub(start, end)`, or `.takeWhile()` to cease listening. Otherwise, the listener remains active.
151
+
152
+ 2. **Terminal operations** (`.toArray()`, `.count()`, `.average()`, `.reduce()`, `.findFirst()`, etc.) are **only available after** conversion to a collector:
153
+ ```typescript
154
+ .toUnordered() // O(n) time & space, no sorting
155
+ // or
156
+ .toOrdered() // Sorted, maintains order
157
+ ```
158
+
159
+ ---
160
+
161
+ ### Performance Characteristics
162
+
163
+ | Collector | Time Complexity | Space Complexity | Sorted? | Best For |
164
+ | :--- | :--- | :--- | :--- | :--- |
165
+ | `toUnordered()` | O(n) | O(n) | No | Raw speed, order not required. |
166
+ | `toOrdered()` | O(2n) | O(n) | Yes | Stable ordering, indexed access, analytics. |
167
+ | `toNumericStatistics()` | O(2n) | O(n) | Yes | Statistical operations requiring sorted data. |
168
+ | `toBigIntStatistics()` | O(2n) | O(n) | Yes | Statistical operations for bigint. |
169
+ | `toWindow()` | O(2n) | O(n) | Yes | Time-based windowing operations. |
170
+
171
+ Opt for `toUnordered()` when speed is paramount. Use `toOrdered()` only when you require stable ordering or statistical methods that depend on sorted data.
172
+
173
+ ---
174
+
175
+ **Comparison with Other Front-End Stream Processors**
176
+
177
+ | Feature | Semantic-TypeScript | RxJS | Native Async Iterators / Generators | Most.js |
178
+ | :--- | :--- | :--- | :--- | :--- |
179
+ | **TypeScript Integration** | First-class, deeply typed with native index awareness. | Excellent, but involves complex generics. | Good, requires manual typing. | Strong, functional-first style. |
180
+ | **Built-in Statistical Analysis** | Comprehensive native support for `number` and `bigint`. | Not available natively (requires custom operators). | None. | None. |
181
+ | **Indexing & Position Awareness** | Native, powerful bigint indexing on every element. | Requires custom operators (`scan`, `withLatestFrom`). | Manual counter required. | Basic, no built-in index. |
182
+ | **Event Stream Management** | Dedicated, type-safe factories with explicit early-stop control. | Powerful but requires manual subscription management. | Manual event listener + cancellation. | Good `fromEvent`, lightweight. |
183
+ | **Performance & Memory Efficiency** | Exceptional optimised `toUnordered()` and `toOrdered()` collectors. | Very good, but operator chains add overhead. | Excellent (zero overhead). | Excellent. |
184
+ | **Bundle Size** | Very lightweight. | Large (even with tree-shaking). | Zero (native). | Small. |
185
+ | **API Design Philosophy** | Functional collector pattern with explicit indexing. | Reactive Observable pattern. | Iterator / Generator pattern. | Functional, point-free. |
186
+ | **Early Termination & Control** | Explicit (`interrupt`, `.limit()`, `.takeWhile()`, `.sub()`). | Good (`take`, `takeUntil`, `first`). | Manual (`break` in `for await…of`). | Good (`take`, `until`). |
187
+ | **Synchronous & Asynchronous Support** | Unified API first-class support for both. | Primarily asynchronous. | Both, but manual. | Primarily asynchronous. |
188
+ | **Learning Curve** | Gentle for developers familiar with functional and indexed pipelines. | Steeper (many operators, hot/cold observables). | Low. | Moderate. |
189
+
190
+ **Key Advantages of Semantic-TypeScript**
191
+
192
+ * Unique built-in statistical and indexing capabilities, eliminating the need for manual `reduce` or external libraries.
193
+ * Explicit control over event streams prevents the memory leaks common in RxJS.
194
+ * A unified synchronous/asynchronous design provides a single, consistent API for diverse use cases.
195
+
196
+ This comparison illustrates why Semantic-TypeScript is particularly well-suited for modern TypeScript front-end applications that demand performance, type safety, and rich analytics without the ceremony of traditional reactive libraries.
197
+
198
+ ---
199
+
200
+ ### Ready to Explore?
201
+
202
+ Semantic-TypeScript transforms complex data flows into readable, composable, and high-performance pipelines. Whether you are handling real-time UI events, processing large datasets, or building analytics dashboards, it provides the power of database-grade indexing with the elegance of functional programming.
203
+
204
+ **Next Steps:**
205
+
206
+ * Browse the fully typed API in your IDE (all exports are from the main package).
207
+ * Join the growing community of developers who have replaced convoluted async iterators with clean Semantic pipelines.
208
+
209
+ **Semantic-TypeScript** — where streams meet structure.
210
+
211
+ Begin building today and experience the difference that thoughtful indexing delivers.
212
+
213
+ **Build with clarity, proceed with confidence, and transform data with intent.**