semantic-typescript 0.5.3 → 0.6.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/dist/asynchronous/collector.d.ts +231 -0
- package/dist/asynchronous/collector.js +800 -0
- package/dist/asynchronous/semantic.d.ts +257 -0
- package/dist/asynchronous/semantic.js +1853 -0
- package/dist/factory.d.ts +71 -37
- package/dist/factory.js +443 -262
- package/dist/guard.d.ts +24 -14
- package/dist/guard.js +73 -19
- package/dist/hook.d.ts +6 -6
- package/dist/hook.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/optional.d.ts +2 -2
- package/dist/symbol.d.ts +19 -10
- package/dist/symbol.js +19 -10
- package/dist/synchronous/collector.d.ts +232 -0
- package/dist/{collector.js → synchronous/collector.js} +160 -151
- package/dist/{semantic.d.ts → synchronous/semantic.d.ts} +111 -120
- package/dist/{semantic.js → synchronous/semantic.js} +299 -337
- package/dist/utility.d.ts +7 -1
- package/dist/utility.js +1 -0
- package/package.json +1 -1
- package/readme.cn.md +158 -697
- package/readme.de.md +163 -432
- package/readme.es.md +163 -433
- package/readme.fr.md +162 -444
- package/readme.jp.md +162 -442
- package/readme.kr.md +161 -430
- package/readme.md +157 -1009
- package/readme.ru.md +161 -426
- package/readme.tw.md +161 -436
- package/dist/collector.d.ts +0 -236
- package/dist/main.d.ts +0 -1
- package/dist/main.js +0 -4
- package/dist/map.d.ts +0 -76
- package/dist/map.js +0 -245
- package/dist/node.d.ts +0 -182
- package/dist/node.js +0 -918
- package/dist/set.d.ts +0 -19
- package/dist/set.js +0 -65
- package/dist/tree.d.ts +0 -82
- package/dist/tree.js +0 -257
package/readme.md
CHANGED
|
@@ -1,1066 +1,214 @@
|
|
|
1
|
-
# Semantic-TypeScript Stream Processing Library
|
|
1
|
+
# Semantic-TypeScript: A Paradigm-Shifting Stream Processing Library
|
|
2
2
|
|
|
3
3
|
## Introduction
|
|
4
|
+
Semantic-TypeScript represents a significant advancement in stream processing technology, synthesising the most effective concepts from JavaScript GeneratorFunctions, Java Streams, and database indexing paradigms. Its foundational design principle is centred on constructing exceptionally efficient data processing pipelines through sophisticated, lazy evaluation and intelligent indexing. The library delivers a rigorously type-safe, functionally pure streaming operation experience specifically engineered for contemporary TypeScript and JavaScript development.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
In contrast to conventional synchronous processing architectures, Semantic-TypeScript implements a unified model that gracefully handles both synchronous (Iterable) and asynchronous (AsyncIterable) data sources. During stream generation, the flow and termination of data are precisely controlled by callback mechanisms, enabling the library to handle with exceptional grace:
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
- Real-time data streams (DOM events, WebSockets, intervals) with deterministic control
|
|
9
|
+
- Large-scale datasets through memory-efficient, lazy pipelines
|
|
10
|
+
- Complex data transformations with a fluent, declarative API
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
The library's innovative approach fundamentally reimagines how developers interact with sequences of data, providing both unprecedented performance characteristics and developer ergonomics in a single, cohesive package.
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
- **Asynchronous data sources** with guaranteed consistency and reliability
|
|
14
|
+
## Core Philosophy: Separation of Definition and Execution
|
|
15
|
+
A key architectural insight of Semantic-TypeScript is the clear separation between a stream's definition and its execution:
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
- **Semantic<E>**: An immutable, lazy blueprint of a data transformation pipeline. It defines what operations (filter, map, etc.) will be performed
|
|
18
|
+
- **Collectable<E>**: A materialised, executable view of the stream. It is obtained from a Semantic and provides all terminal operations (collect, forEach, etc.) to execute the pipeline and produce a result
|
|
16
19
|
|
|
17
|
-
|
|
20
|
+
This separation enforces a clean mental model and unlocks powerful optimisations, such as choosing an UnorderedCollectable to skip unnecessary sorting for maximum speed.
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
## Why Choose Semantic-TypeScript?
|
|
23
|
+
Selecting the right library for data stream processing involves balancing performance, type safety, and expressiveness. Semantic-TypeScript is engineered to excel across all these dimensions.
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
### 1. A Unified, Type-Safe Paradigm for All Data Sequences
|
|
26
|
+
It provides a consistent, declarative API for processing any data sequence—be 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
27
|
|
|
24
|
-
|
|
25
|
-
At its core, the library is built on
|
|
28
|
+
### 2. Uncompromising Performance with Intelligent Laziness
|
|
29
|
+
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 is invoked. This is coupled with short-circuiting capabilities (via limit, anyMatch, or custom interrupt callbacks), which allows processing to stop early, dramatically improving efficiency for large or infinite streams.
|
|
26
30
|
|
|
27
|
-
|
|
28
|
-
|
|
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
|
+
### 3. The Power of the `Collector<E, A, R>` Pattern
|
|
32
|
+
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 (toArray, groupBy, summate, etc.) for everyday tasks, while making it trivial to implement your own complex, reusable reduction logic. This is far more powerful and composable than a fixed set of terminal methods.
|
|
31
33
|
|
|
32
|
-
|
|
34
|
+
### 4. First-Class Support for Modern Web & Async Data
|
|
35
|
+
Semantic-TypeScript is designed for contemporary development. It offers native factory methods for modern web sources:
|
|
33
36
|
|
|
34
|
-
|
|
35
|
-
|
|
37
|
+
- `useFrom(iterable)`, `useRange()` for static data
|
|
38
|
+
- `useInterval()`, `useAnimationFrame()` for time-based streams
|
|
39
|
+
- `useBlob()` for chunked binary data processing
|
|
40
|
+
- `useWebSocket()`, `useDocument()`, `useWindow()` for real-time event streams
|
|
36
41
|
|
|
37
|
-
|
|
38
|
-
|
|
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.
|
|
42
|
+
### 5. Beyond Basic Aggregation: Built-in Statistical Analysis
|
|
43
|
+
Move beyond simple sums and averages. The library provides dedicated NumericStatistics and BigIntStatistics interfaces, offering immediate access to advanced statistical measures directly from your streams—variance, standard deviation, median, skewness, and kurtosis. This turns complex data analysis into a one-liner.
|
|
44
44
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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.**
|
|
45
|
+
### 6. Designed for Developer Ergonomics
|
|
46
|
+
- **Fluent, Chainable API**: Write complex data pipelines as readable, sequential chains
|
|
47
|
+
- **Comprehensive Utility Suite**: Essential guards (isFunction, isIterable), utilities (useCompare, useTraverse), and functional interfaces included
|
|
48
|
+
- **Optional<T> Integration**: Safely models the absence of a value, eliminating null-pointer concerns
|
|
49
|
+
- **Performance Guidance**: Clear guidance on when to use unordered collection for speed versus ordered for sequence
|
|
58
50
|
|
|
59
51
|
## Installation
|
|
60
|
-
|
|
61
52
|
```bash
|
|
62
53
|
npm install semantic-typescript
|
|
63
54
|
```
|
|
64
55
|
|
|
65
|
-
##
|
|
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) |
|
|
56
|
+
## Core Concepts in Practice
|
|
115
57
|
|
|
116
|
-
|
|
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) |
|
|
58
|
+
### 1. Creating Streams (Semantic)
|
|
59
|
+
Streams can be created from various sources using factory functions.
|
|
157
60
|
|
|
158
61
|
```typescript
|
|
159
|
-
|
|
160
|
-
let value: unknown = "hello";
|
|
161
|
-
|
|
162
|
-
if (isString(value)) {
|
|
163
|
-
console.log(value.length); // Type-safe, value inferred as string
|
|
164
|
-
}
|
|
62
|
+
import { useFrom, useInterval, useDocument } from 'semantic-typescript';
|
|
165
63
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
}
|
|
64
|
+
// From a static array
|
|
65
|
+
const staticStream = useFrom([1, 2, 3, 4, 5]);
|
|
169
66
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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.
|
|
67
|
+
// From an asynchronous generator
|
|
68
|
+
const asyncStream = useFrom(async function*() {
|
|
69
|
+
yield 1;
|
|
70
|
+
yield 2;
|
|
220
71
|
});
|
|
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
72
|
|
|
265
|
-
|
|
73
|
+
// A time-based stream
|
|
74
|
+
const tickStream = useInterval(1000); // emits every second
|
|
266
75
|
|
|
267
|
-
|
|
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
|
|
76
|
+
// A DOM event stream (see crucial note below)
|
|
77
|
+
const clickStream = useDocument('click');
|
|
330
78
|
```
|
|
331
79
|
|
|
332
|
-
|
|
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
|
-
|
|
80
|
+
### 2. Transforming Streams (Intermediate Operations)
|
|
81
|
+
Operations are lazily chained to define the pipeline.
|
|
349
82
|
|
|
350
83
|
```typescript
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
//
|
|
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"
|
|
84
|
+
const processedStream = staticStream
|
|
85
|
+
.filter(x => x % 2 === 0) // Keep only even numbers
|
|
86
|
+
.map(x => x * 10) // Multiply by 10
|
|
87
|
+
.flatMap(x => [x, x + 1]) // Transform each element into two
|
|
88
|
+
.distinct(); // Remove duplicates
|
|
369
89
|
|
|
370
|
-
//
|
|
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);
|
|
90
|
+
// Nothing has been executed yet
|
|
378
91
|
```
|
|
379
92
|
|
|
380
|
-
###
|
|
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) |
|
|
93
|
+
### 3. Executing Streams (Terminal Operations)
|
|
94
|
+
To get a result, you must obtain a Collectable and invoke a terminal operation.
|
|
501
95
|
|
|
502
96
|
```typescript
|
|
503
|
-
//
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
//
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
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
|
|
97
|
+
// Get an unordered collectable for performance
|
|
98
|
+
const resultArray = await processedStream.toUnordered().toArray();
|
|
99
|
+
console.log(resultArray); // e.g., [20, 21, 40, 41]
|
|
100
|
+
|
|
101
|
+
// Use a built-in collector
|
|
102
|
+
const sum = await processedStream.toUnordered().collect(useSummate());
|
|
103
|
+
console.log(sum);
|
|
104
|
+
|
|
105
|
+
// Or use the generic collect method
|
|
106
|
+
const customResult = await processedStream.toOrdered().collect(
|
|
107
|
+
() => new Map<number, number>(),
|
|
108
|
+
(map, element, index) => map.set(index, element),
|
|
109
|
+
map => map
|
|
850
110
|
);
|
|
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
111
|
```
|
|
859
112
|
|
|
860
|
-
|
|
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) |
|
|
113
|
+
### 4. Crucial: Working with Event Streams
|
|
114
|
+
Event streams (useDocument, useWindow, useHTMLElement, useWebSocket) are infinite by nature. You must use operations like sub, takeWhile, or limit to define when to stop collecting events and complete the stream. Otherwise, the terminal operation will wait indefinitely.
|
|
952
115
|
|
|
953
116
|
```typescript
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
117
|
+
import { useDocument } from 'semantic-typescript';
|
|
118
|
+
|
|
119
|
+
// Collect only the first 5 clicks
|
|
120
|
+
const first5Clicks = await useDocument('click')
|
|
121
|
+
.limit(5) // <- Essential: limits the stream to 5 events
|
|
122
|
+
.toUnordered()
|
|
123
|
+
.toArray();
|
|
124
|
+
|
|
125
|
+
// Collect clicks for a 10-second window
|
|
126
|
+
const clicksIn10s = await useDocument('click')
|
|
127
|
+
.takeWhile((_, index, startTime = Date.now()) => Date.now() - startTime < 10000)
|
|
128
|
+
.toUnordered()
|
|
129
|
+
.toArray();
|
|
130
|
+
|
|
131
|
+
// Collect clicks from index 2 to 5 (0-based)
|
|
132
|
+
const specificClicks = await useDocument('click')
|
|
133
|
+
.sub(2n, 6n) // <- Takes elements with index 2, 3, 4, 5
|
|
134
|
+
.toUnordered()
|
|
135
|
+
.toArray();
|
|
971
136
|
```
|
|
972
137
|
|
|
973
|
-
|
|
138
|
+
**Key Insight**: The event (e.g., a MouseEvent) and its sequential firing index (as a bigint) are passed together through the pipeline via the `accept(event, index)` callback.
|
|
974
139
|
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
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) |
|
|
140
|
+
### 5. Leveraging Statistics
|
|
141
|
+
```typescript
|
|
142
|
+
const numericStream = useFrom([10, 20, 30, 40, 50]).toNumeric();
|
|
1019
143
|
|
|
1020
|
-
|
|
144
|
+
const average = await numericStream.average();
|
|
145
|
+
const median = await numericStream.median();
|
|
146
|
+
const standardDeviation = await numericStream.standardDeviation();
|
|
147
|
+
const skewness = await numericStream.skewness();
|
|
1021
148
|
|
|
1022
|
-
|
|
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
|
|
149
|
+
console.log(`Average: ${average}, Median: ${median}, StdDev: ${standardDeviation}`);
|
|
1029
150
|
```
|
|
1030
151
|
|
|
1031
|
-
|
|
152
|
+
## Main Features
|
|
153
|
+
- **Dual Stream Types**: Full support for both SynchronousSemantic (for Iterable) and AsynchronousSemantic (for AsyncIterable and events)
|
|
154
|
+
- **Rich Operation Set**: filter, map, flatMap, concat, distinct, sorted, limit, skip, peek, reverse, shuffle
|
|
155
|
+
- **Flexible Terminal Operations**: collect (with custom collectors), toArray, toSet, toMap, forEach, reduce, findFirst, anyMatch, allMatch, count
|
|
156
|
+
- **Advanced Collectors**: Built-in collectors for joining, groupingBy, partitioningBy, summing, averaging, maxBy, minBy
|
|
157
|
+
- **Statistical Module**: Ready-to-use methods for mean, median, mode, variance, standardDeviation, range, quantiles, skewness, kurtosis on numeric/bigint streams
|
|
158
|
+
- **Utility Functions**: Type guards (isPromise, isAsyncIterable), comparators (useCompare), traversal (useTraverse), and conversion hooks
|
|
159
|
+
- **Optional<T>**: A monadic container for nullable values, integrated with find operations
|
|
160
|
+
|
|
161
|
+
## API Overview
|
|
162
|
+
### Core Classes & Interfaces
|
|
163
|
+
- `Semantic<E>` / `AsynchronousSemantic<E>`: The abstract stream definition
|
|
164
|
+
- `Collectable<E>` / `AsynchronousCollectable<E>`: The executable stream with terminal operations
|
|
165
|
+
- `OrderedCollectable<E>` / `UnorderedCollectable<E>`: Materialised versions optimised for order-sensitive or order-insensitive operations
|
|
166
|
+
- `Collector<E, A, R>`: The abstraction for mutable reduction operations
|
|
167
|
+
|
|
168
|
+
### Factory Functions (use*)
|
|
169
|
+
- **From Sources**: useFrom, useRange, useFill, useEmpty
|
|
170
|
+
- **From Time**: useInterval, useAnimationFrame
|
|
171
|
+
- **From Web APIs**: useBlob, useDocument, useWindow, useHTMLElement, useWebSocket
|
|
172
|
+
- **Collectors**: useToArray, useGroupBy, useSummate, useJoin, etc.
|
|
173
|
+
|
|
174
|
+
## Performance Notes
|
|
175
|
+
- **Lazy Evaluation**: Pipelines are composed without execution until a terminal operation is called
|
|
176
|
+
- **Short-Circuiting**: Operations like limit, anyMatch, and findFirst will stop processing elements as soon as the result is determined
|
|
177
|
+
- **Ordered vs Unordered**:
|
|
178
|
+
- Use `.toUnordered()` for terminal operations when the order of the source elements does not matter to your result (e.g., for sum, max, or toSet). This can allow internal optimisations that skip costly sorting steps
|
|
179
|
+
- Use `.toOrdered()` when sequence is important (e.g., for toArray where order must be preserved)
|
|
180
|
+
|
|
181
|
+
## Getting Started Example
|
|
1032
182
|
```typescript
|
|
1033
|
-
|
|
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
|
-
```
|
|
183
|
+
import { useFrom, useSummate, useGroupBy } from 'semantic-typescript';
|
|
1044
184
|
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
185
|
+
interface Transaction {
|
|
186
|
+
id: number;
|
|
187
|
+
amount: number;
|
|
188
|
+
category: string;
|
|
189
|
+
}
|
|
1050
190
|
|
|
1051
|
-
|
|
1052
|
-
|
|
191
|
+
const transactions: Transaction[] = [
|
|
192
|
+
{ id: 1, amount: 100, category: 'Food' },
|
|
193
|
+
{ id: 2, amount: 200, category: 'Electronics' },
|
|
194
|
+
{ id: 3, amount: 50, category: 'Food' },
|
|
195
|
+
{ id: 4, amount: 300, category: 'Electronics' },
|
|
196
|
+
];
|
|
197
|
+
|
|
198
|
+
// Calculate total amount per category
|
|
199
|
+
const totalsByCategory = await useFrom(transactions)
|
|
200
|
+
.toUnordered()
|
|
201
|
+
.collect(
|
|
202
|
+
useGroupBy(
|
|
203
|
+
t => t.category,
|
|
204
|
+
t => t.amount,
|
|
205
|
+
useSummate() // Collector for the values
|
|
206
|
+
)
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
console.log(totalsByCategory); // Map { 'Food' => 150, 'Electronics' => 500 }
|
|
1053
210
|
```
|
|
1054
211
|
|
|
1055
|
-
|
|
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.
|
|
212
|
+
Semantic-TypeScript is built for developers who seek a rigorously designed, type-safe, and high-performance stream processing library. It brings the power of enterprise-level data transformation patterns to the TypeScript ecosystem, perfectly suited for data-intensive front-end applications, Node.js data processing, and any scenario where elegant, efficient handling of sequences is required.
|
|
1066
213
|
|
|
214
|
+
[](https://github.com/eloyhere/semantic-typescript) [](https://www.npmjs.com/package/semantic-typescript)
|