functype 1.27.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1139 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +279 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1243 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +7 -12
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-0XJEOHi_.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BTLBc-KK.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { Either } from "../either/index.js";
|
|
2
|
+
import { Extractable } from "../extractable/Extractable.js";
|
|
3
|
+
import { FunctypeBase } from "../functype/Functype.js";
|
|
4
|
+
import { Option } from "../option/index.js";
|
|
5
|
+
import { Pipe } from "../pipe/index.js";
|
|
6
|
+
import { SerializedError } from "../serialization/error-envelope.js";
|
|
7
|
+
import { Try } from "../try/index.js";
|
|
8
|
+
import { Type } from "../types/index.js";
|
|
9
|
+
/**
|
|
10
|
+
* Lazy type module
|
|
11
|
+
* @module Lazy
|
|
12
|
+
* @category Core
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* The Lazy type represents a computation that is deferred until needed.
|
|
16
|
+
* It provides memoization and safe evaluation with integration to Option, Either, and Try.
|
|
17
|
+
* @typeParam T - The type of the value to be computed
|
|
18
|
+
*/
|
|
19
|
+
export interface Lazy<out T extends Type> extends FunctypeBase<T, "Lazy">, Extractable<T>, Pipe<T> {
|
|
20
|
+
/** Tag identifying this as a Lazy type */
|
|
21
|
+
readonly _tag: "Lazy";
|
|
22
|
+
/** Whether the computation has been evaluated */
|
|
23
|
+
readonly isEvaluated: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Returns the computed value, or calls `defaultValue` if the computation fails.
|
|
26
|
+
* The default is lazy: it runs only on failure. A default that fits `T` keeps `T`, so a literal
|
|
27
|
+
* union is not widened; a default of another type widens the result to `T | T2`
|
|
28
|
+
* (Scala: `getOrElse[B >: A](default: => B): B`).
|
|
29
|
+
*/
|
|
30
|
+
getOrElse<T2 extends Type = never>(defaultValue: () => T | T2): T | T2;
|
|
31
|
+
/**
|
|
32
|
+
* Returns the computed value or null if computation fails
|
|
33
|
+
* @returns The computed value or null
|
|
34
|
+
*/
|
|
35
|
+
orNull(): T | null;
|
|
36
|
+
/**
|
|
37
|
+
* Returns the computed value or throws an error if computation fails
|
|
38
|
+
* @param error - Optional custom error to throw. If not provided, throws the computation error or a default error
|
|
39
|
+
* @returns The computed value
|
|
40
|
+
* @throws The specified error, computation error, or a default error
|
|
41
|
+
*/
|
|
42
|
+
orThrow(error?: Error): T;
|
|
43
|
+
/**
|
|
44
|
+
* Returns this Lazy if computation succeeds, otherwise calls `alternative` for another Lazy.
|
|
45
|
+
* The alternative is lazy: it runs only on failure. It may carry a different type; result is `Lazy<T | T2>`.
|
|
46
|
+
*/
|
|
47
|
+
orElse<T2 extends Type>(alternative: () => Lazy<T2>): Lazy<T | T2>;
|
|
48
|
+
/**
|
|
49
|
+
* Maps the value inside the Lazy using the provided function
|
|
50
|
+
* @param f - The mapping function
|
|
51
|
+
* @returns A new Lazy containing the mapped value
|
|
52
|
+
*/
|
|
53
|
+
map<U extends Type>(f: (value: T) => U): Lazy<U>;
|
|
54
|
+
/**
|
|
55
|
+
* Applies a wrapped function to a wrapped value (Applicative pattern)
|
|
56
|
+
* @param ff - A Lazy containing a function from T to U
|
|
57
|
+
* @returns A new Lazy containing the result
|
|
58
|
+
*/
|
|
59
|
+
ap<U extends Type>(ff: Lazy<(value: T) => U>): Lazy<U>;
|
|
60
|
+
/**
|
|
61
|
+
* Maps the value inside the Lazy using an async function
|
|
62
|
+
* @param f - The async mapping function
|
|
63
|
+
* @returns A Promise of a new Lazy containing the mapped value
|
|
64
|
+
*/
|
|
65
|
+
mapAsync<U extends Type>(f: (value: T) => Promise<U>): Promise<Lazy<U>>;
|
|
66
|
+
/**
|
|
67
|
+
* Maps the value using a function that returns a Lazy
|
|
68
|
+
* @param f - The mapping function returning a Lazy
|
|
69
|
+
* @returns A new Lazy containing the flattened result
|
|
70
|
+
*/
|
|
71
|
+
flatMap<U extends Type>(f: (value: T) => Lazy<U>): Lazy<U>;
|
|
72
|
+
/**
|
|
73
|
+
* Maps the value using an async function that returns a Lazy
|
|
74
|
+
* @param f - The async mapping function returning a Lazy
|
|
75
|
+
* @returns A Promise of a new Lazy containing the flattened result
|
|
76
|
+
*/
|
|
77
|
+
flatMapAsync<U extends Type>(f: (value: T) => Promise<Lazy<U>>): Promise<Lazy<U>>;
|
|
78
|
+
/**
|
|
79
|
+
* Returns a Lazy that filters the value based on a predicate
|
|
80
|
+
* @param predicate - The predicate function
|
|
81
|
+
* @returns A Lazy containing an Option of the value
|
|
82
|
+
*/
|
|
83
|
+
filter(predicate: (value: T) => boolean): Lazy<Option<T>>;
|
|
84
|
+
/**
|
|
85
|
+
* Recovers from a failed computation by providing an alternative value
|
|
86
|
+
* @param f - Function that takes the error and returns a recovery value
|
|
87
|
+
* @returns A new Lazy that will use the recovery function if computation fails
|
|
88
|
+
*/
|
|
89
|
+
recover(f: (error: unknown) => T): Lazy<T>;
|
|
90
|
+
/**
|
|
91
|
+
* Recovers from a failed computation by providing an alternative Lazy
|
|
92
|
+
* @param f - Function that takes the error and returns a recovery Lazy
|
|
93
|
+
* @returns A new Lazy that will use the recovery Lazy if computation fails
|
|
94
|
+
*/
|
|
95
|
+
recoverWith(f: (error: unknown) => Lazy<T>): Lazy<T>;
|
|
96
|
+
/**
|
|
97
|
+
* Evaluates the computation and returns it as an Option
|
|
98
|
+
* @returns Some containing the value if successful, None if computation fails
|
|
99
|
+
*/
|
|
100
|
+
toOption(): Option<T>;
|
|
101
|
+
/**
|
|
102
|
+
* Evaluates the computation and returns it as an Either
|
|
103
|
+
* @returns Right containing the value if successful, Left containing the error if computation fails
|
|
104
|
+
*/
|
|
105
|
+
toEither(): Either<unknown, T>;
|
|
106
|
+
/**
|
|
107
|
+
* Evaluates the computation and returns it as an Either with a mapped error
|
|
108
|
+
* @param mapError - Function to map the error
|
|
109
|
+
* @returns Right containing the value if successful, Left containing the mapped error if computation fails
|
|
110
|
+
*/
|
|
111
|
+
toEitherWith<E>(mapError: (error: unknown) => E): Either<E, T>;
|
|
112
|
+
/**
|
|
113
|
+
* Evaluates the computation and returns it as a Try
|
|
114
|
+
* @returns Try containing the result of the computation
|
|
115
|
+
*/
|
|
116
|
+
toTry(): Try<T>;
|
|
117
|
+
/**
|
|
118
|
+
* Applies an effect function to the value if computation succeeds
|
|
119
|
+
* @param f - The effect function
|
|
120
|
+
* @returns This Lazy for chaining
|
|
121
|
+
*/
|
|
122
|
+
tap(f: (value: T) => void): Lazy<T>;
|
|
123
|
+
/**
|
|
124
|
+
* Applies an effect function to the error if computation fails
|
|
125
|
+
* @param f - The effect function for errors
|
|
126
|
+
* @returns This Lazy for chaining
|
|
127
|
+
*/
|
|
128
|
+
tapError(f: (error: unknown) => void): Lazy<T>;
|
|
129
|
+
/**
|
|
130
|
+
* Pattern matching on the Lazy value
|
|
131
|
+
* @param f - Function to apply to the computed value
|
|
132
|
+
* @returns The result of applying f to the computed value
|
|
133
|
+
*/
|
|
134
|
+
fold<U>(f: (value: T) => U): U;
|
|
135
|
+
/**
|
|
136
|
+
* Pattern matching with success and failure handlers
|
|
137
|
+
* @param onFailure - Function to handle computation failure
|
|
138
|
+
* @param onSuccess - Function to handle successful computation
|
|
139
|
+
* @returns The result of the appropriate handler
|
|
140
|
+
*/
|
|
141
|
+
foldWith<U>(onFailure: (error: unknown) => U, onSuccess: (value: T) => U): U;
|
|
142
|
+
/**
|
|
143
|
+
* Left fold operation
|
|
144
|
+
* @param z - Initial value
|
|
145
|
+
* @returns Function that takes an operator and applies it
|
|
146
|
+
*/
|
|
147
|
+
foldLeft<B>(z: B): (op: (b: B, a: T) => B) => B;
|
|
148
|
+
/**
|
|
149
|
+
* Right fold operation
|
|
150
|
+
* @param z - Initial value
|
|
151
|
+
* @returns Function that takes an operator and applies it
|
|
152
|
+
*/
|
|
153
|
+
foldRight<B>(z: B): (op: (a: T, b: B) => B) => B;
|
|
154
|
+
/**
|
|
155
|
+
* Pattern matching for the Lazy type
|
|
156
|
+
* @param patterns - Object with handler for Lazy pattern
|
|
157
|
+
* @returns The result of the matched handler
|
|
158
|
+
*/
|
|
159
|
+
match<R>(patterns: {
|
|
160
|
+
Lazy: (value: T) => R;
|
|
161
|
+
}): R;
|
|
162
|
+
/**
|
|
163
|
+
* Creates a string representation of the Lazy
|
|
164
|
+
* @returns String representation showing evaluation status
|
|
165
|
+
*/
|
|
166
|
+
toString(): string;
|
|
167
|
+
/**
|
|
168
|
+
* Converts the Lazy to a value object.
|
|
169
|
+
*
|
|
170
|
+
* **Forces the thunk** as a side effect — Lazy serialization (and projection
|
|
171
|
+
* to a plain value object) cannot represent an unevaluated thunk in JSON;
|
|
172
|
+
* forcing is the only way to produce a complete projection. If the thunk
|
|
173
|
+
* threw, the failure is captured in the `error` field (real Error, with
|
|
174
|
+
* full prototype intact for in-memory inspection — `toJSON` projects to
|
|
175
|
+
* `SerializedError` for the wire).
|
|
176
|
+
*
|
|
177
|
+
* Changed in 1.2.0 — pre-1.2.0 Lazy emitted `{_tag, evaluated, value?}`
|
|
178
|
+
* without forcing. See `docs/archive/proposals/serializable-audit-q1-q2.md`.
|
|
179
|
+
*/
|
|
180
|
+
toValue(): {
|
|
181
|
+
_tag: "Lazy";
|
|
182
|
+
value: T;
|
|
183
|
+
} | {
|
|
184
|
+
_tag: "Lazy";
|
|
185
|
+
error: Error;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Custom JSON serialization. Forces the thunk (see `toValue` for the
|
|
189
|
+
* side-effect contract). Emits `{"@functype":"Lazy","_tag":"Lazy","value":T}`
|
|
190
|
+
* on success, or `{"@functype":"Lazy","_tag":"Lazy","error":SerializedError}`
|
|
191
|
+
* if the thunk threw — see error-envelope.ts for round-trip semantics.
|
|
192
|
+
*/
|
|
193
|
+
toJSON(): {
|
|
194
|
+
"@functype": "Lazy";
|
|
195
|
+
_tag: "Lazy";
|
|
196
|
+
value: T;
|
|
197
|
+
} | {
|
|
198
|
+
"@functype": "Lazy";
|
|
199
|
+
_tag: "Lazy";
|
|
200
|
+
error: SerializedError;
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/** Builds a Lazy around `thunk`, which doesn't run until a value is read. */
|
|
204
|
+
declare const LazyConstructor: <T extends Type>(thunk: () => T) => Lazy<T>;
|
|
205
|
+
declare const LazyStatics: {
|
|
206
|
+
/**
|
|
207
|
+
* Creates a Lazy from a thunk (deferred computation)
|
|
208
|
+
* @param thunk - Function that computes the value
|
|
209
|
+
* @returns A new Lazy instance
|
|
210
|
+
*/
|
|
211
|
+
of: <T extends Type>(thunk: () => T) => Lazy<T>;
|
|
212
|
+
/**
|
|
213
|
+
* Creates a Lazy from an immediate value
|
|
214
|
+
* @param value - The value to wrap
|
|
215
|
+
* @returns A new Lazy instance that returns the value
|
|
216
|
+
*/
|
|
217
|
+
fromValue: <T extends Type>(value: T) => Lazy<T>;
|
|
218
|
+
/**
|
|
219
|
+
* Creates a Lazy from an Option
|
|
220
|
+
* @param option - The Option to convert
|
|
221
|
+
* @param defaultThunk - Thunk to compute default value if Option is None
|
|
222
|
+
* @returns A new Lazy instance
|
|
223
|
+
*/
|
|
224
|
+
fromOption: <T extends Type>(option: Option<T>, defaultThunk: () => T) => Lazy<T>;
|
|
225
|
+
/**
|
|
226
|
+
* Creates a Lazy from a Try
|
|
227
|
+
* @param tryValue - The Try to convert
|
|
228
|
+
* @returns A new Lazy instance
|
|
229
|
+
*/
|
|
230
|
+
fromTry: <T extends Type>(tryValue: Try<T>) => Lazy<T>;
|
|
231
|
+
/**
|
|
232
|
+
* Creates a Lazy from an Either
|
|
233
|
+
* @param either - The Either to convert
|
|
234
|
+
* @returns A new Lazy instance
|
|
235
|
+
*/
|
|
236
|
+
fromEither: <E, T extends Type>(either: Either<E, T>) => Lazy<T>;
|
|
237
|
+
/**
|
|
238
|
+
* Creates a Lazy that will throw an error since promises need to be awaited first
|
|
239
|
+
* @param promise - The Promise to convert
|
|
240
|
+
* @returns A new Lazy instance that throws an error
|
|
241
|
+
*/
|
|
242
|
+
fromPromise: <T extends Type>(_promise: Promise<T>) => Lazy<T>;
|
|
243
|
+
/**
|
|
244
|
+
* Creates a failed Lazy that will throw when evaluated
|
|
245
|
+
* @param error - The error to throw
|
|
246
|
+
* @returns A new Lazy instance that throws the error
|
|
247
|
+
*/
|
|
248
|
+
fail: <T extends Type>(error: unknown) => Lazy<T>;
|
|
249
|
+
/**
|
|
250
|
+
* Creates an already-evaluated Lazy. Used by `fromJSON` to reconstruct a
|
|
251
|
+
* Lazy whose thunk was forced at serialize time — there is no original
|
|
252
|
+
* thunk to defer because a closure cannot be JSON-serialized.
|
|
253
|
+
*
|
|
254
|
+
* Functionally equivalent to `Lazy.fromValue` but reads with intent at
|
|
255
|
+
* the call site.
|
|
256
|
+
*/
|
|
257
|
+
evaluated: <T extends Type>(value: T) => Lazy<T>;
|
|
258
|
+
/**
|
|
259
|
+
* Reconstruct a Lazy from a JSON envelope emitted by `serialize().toJSON()`
|
|
260
|
+
* or instance `toJSON()`. Verifies `@functype === "Lazy"`. Success envelopes
|
|
261
|
+
* become already-evaluated Lazies via `Lazy.evaluated`; failure envelopes
|
|
262
|
+
* become Lazies whose forcing rethrows the deserialized Error (see
|
|
263
|
+
* error-envelope.ts — `instanceof SomeError` does NOT survive but `name`
|
|
264
|
+
* does).
|
|
265
|
+
*/
|
|
266
|
+
fromJSON: <T extends Type>(json: string) => Lazy<T>;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* Creates a Lazy computation that defers evaluation until needed.
|
|
270
|
+
* Results are memoized after first evaluation.
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* // Basic lazy evaluation
|
|
274
|
+
* const expensive = Lazy(() => {
|
|
275
|
+
* console.log("Computing...")
|
|
276
|
+
* return 42
|
|
277
|
+
* })
|
|
278
|
+
* // Nothing printed yet
|
|
279
|
+
* const result = expensive.orThrow() // Prints "Computing..." and returns 42
|
|
280
|
+
* const cached = expensive.orThrow() // Returns 42 without printing
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* // Error handling
|
|
284
|
+
* const risky = Lazy(() => {
|
|
285
|
+
* if (Math.random() > 0.5) throw new Error("Failed")
|
|
286
|
+
* return "Success"
|
|
287
|
+
* })
|
|
288
|
+
* const safe = risky.getOrElse(() => "Default") // Returns "Success" or "Default"
|
|
289
|
+
* const option = risky.toOption() // Some("Success") or None
|
|
290
|
+
* const either = risky.toEither() // Right("Success") or Left(Error)
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* // Chaining computations
|
|
294
|
+
* const result = Lazy(() => 10)
|
|
295
|
+
* .map(x => x * 2)
|
|
296
|
+
* .flatMap(x => Lazy(() => x + 5))
|
|
297
|
+
* .recover(err => 0)
|
|
298
|
+
* .orThrow() // 25
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* // Integration with functype
|
|
302
|
+
* const userOption = Option({ id: 1, name: "Alice" })
|
|
303
|
+
* const userName = Lazy.fromOption(userOption, () => ({ id: 0, name: "Anonymous" }))
|
|
304
|
+
* .map(user => user.name)
|
|
305
|
+
* .orThrow() // "Alice"
|
|
306
|
+
*/
|
|
307
|
+
export declare const Lazy: LazyCompanion;
|
|
308
|
+
/** The type of `Lazy`: its constructor and its statics, named so that errors and hovers print `LazyCompanion`. */
|
|
309
|
+
export interface LazyCompanion extends LazyConstructorType, LazyStaticsType {}
|
|
310
|
+
type LazyConstructorType = typeof LazyConstructor;
|
|
311
|
+
type LazyStaticsType = typeof LazyStatics;
|
|
312
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{define as r}from"../internal/define.js";import{safeStringify as i}from"../internal/stringify.js";import{None as a,Some as o}from"../option/index.js";import{createSerializer as s,createTaggedSerializer as c}from"../serialization/SerializationCompanion.js";import{deserializeError as l,serializeError as u}from"../serialization/error-envelope.js";import{Try as d}from"../try/index.js";const f=e=>{let{state:t}=e;if(t._tag!==`Pending`)return t;let n=p(t.thunk);return Reflect.set(e,`state`,n),n},p=e=>{try{return{_tag:`Evaluated`,value:e()}}catch(e){return{_tag:`Failed`,error:e}}},m=e=>{let t=f(e);if(t._tag===`Failed`)throw t.error;return t.value},h=r()(`Lazy`,{[Symbol.toStringTag]:`Lazy`,get isEvaluated(){return this.state._tag!==`Pending`},getOrElse(e){let t=f(this);return t._tag===`Evaluated`?t.value:e()},orNull(){let e=f(this);return e._tag===`Evaluated`?e.value:null},orUndefined(){let e=f(this);return e._tag===`Evaluated`?e.value:void 0},orThrow(e){let t=f(this);if(t._tag===`Failed`)throw e??t.error;return t.value},orElse(e){return g(()=>{let t=f(this);return t._tag===`Evaluated`?t.value:e().orThrow()})},map(e){return g(()=>e(m(this)))},ap(e){return g(()=>e.orThrow()(m(this)))},async mapAsync(e){let t=await e(m(this));return g(()=>t)},flatMap(e){return g(()=>e(m(this)).orThrow())},async flatMapAsync(e){let t=await e(m(this));return g(()=>t.orThrow())},filter(e){return g(()=>{let t=m(this);return e(t)?o(t):a()})},recover(e){return g(()=>{let t=f(this);return t._tag===`Evaluated`?t.value:e(t.error)})},recoverWith(e){return g(()=>{let t=f(this);return t._tag===`Evaluated`?t.value:e(t.error).orThrow()})},toOption(){let e=f(this);return e._tag===`Evaluated`?o(e.value):a()},toEither(){let e=f(this);return e._tag===`Evaluated`?n(e.value):t(e.error)},toEitherWith(e){let r=f(this);return r._tag===`Evaluated`?n(r.value):t(e(r.error))},toTry(){return d(()=>m(this))},tap(e){return g(()=>{let t=m(this);return e(t),t})},tapError(e){return g(()=>{let t=f(this);if(t._tag===`Evaluated`)return t.value;throw e(t.error),t.error})},fold(e){return e(m(this))},foldWith(e,t){let n=f(this);if(n._tag===`Failed`)return e(n.error);try{return t(n.value)}catch(t){return e(t)}},foldLeft(e){return t=>t(e,m(this))},foldRight(e){return t=>t(m(this),e)},match(e){return e.Lazy(m(this))},toString(){let{state:e}=this;return e._tag===`Evaluated`?`Lazy(${i(e.value)})`:e._tag===`Failed`?`Lazy(<error: ${e.error instanceof Error?e.error.message:String(e.error)}>)`:`Lazy(<not evaluated>)`},toValue(){let e=f(this);if(e._tag===`Evaluated`)return{_tag:`Lazy`,value:e.value};let{error:t}=e;return{_tag:`Lazy`,error:t instanceof Error?t:Error(String(t))}},get size(){return+(f(this)._tag===`Evaluated`)},get isEmpty(){return f(this)._tag===`Failed`},contains(e){let t=f(this);return t._tag===`Evaluated`&&t.value===e},reduce(){return m(this)},reduceRight(){return m(this)},count(e){let t=f(this);if(t._tag===`Failed`)return 0;try{return+!!e(t.value)}catch{return 0}},find(e){let t=f(this);if(t._tag===`Failed`)return a();try{return e(t.value)?o(t.value):a()}catch{return a()}},exists(e){let t=f(this);if(t._tag===`Failed`)return!1;try{return e(t.value)}catch{return!1}},forEach(e){let t=f(this);if(t._tag!==`Failed`)try{e(t.value)}catch{}},pipe(e){return e(m(this))},toJSON(){let e=f(this);return e._tag===`Evaluated`?{"@functype":`Lazy`,_tag:`Lazy`,value:e.value}:{"@functype":`Lazy`,_tag:`Lazy`,error:u(e.error)}},serialize(){let e=f(this);if(e._tag===`Failed`)return c(`Lazy`,`Lazy`,{error:u(e.error)});try{return s(`Lazy`,e.value)}catch(e){return c(`Lazy`,`Lazy`,{error:u(e)})}}}),g=e=>{let t=Object.create(h);return t._tag=`Lazy`,t.state={_tag:`Pending`,thunk:e},t},_={of:e=>g(e),fromValue:e=>g(()=>e),fromOption:(e,t)=>g(()=>e._tag===`Some`?e.value:t()),fromTry:e=>g(()=>e.orThrow()),fromEither:e=>g(()=>e.fold(e=>{throw e},e=>e)),fromPromise:e=>g(()=>{throw Error(`Promise not yet resolved. Use await on the promise before creating Lazy.`)}),fail:e=>g(()=>{throw e}),evaluated:e=>g(()=>e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Lazy`)throw Error(`Lazy.fromJSON: expected @functype="Lazy", got ${JSON.stringify(t[`@functype`])}`);if(t.error!==void 0){let e=typeof t.error==`object`?l(t.error):Error(t.error);return _.fail(e)}return _.evaluated(t.value)}},v=e(g,_);export{v as Lazy};
|
package/dist/lazy/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { Lazy, type Lazy as LazyType };
|
|
1
|
+
import { Lazy, LazyCompanion } from "./Lazy.js";
|
|
2
|
+
export { Lazy, type LazyCompanion, type Lazy as LazyType };
|
package/dist/lazy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export{Lazy}from"./Lazy.js";
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { Foldable } from "../foldable/Foldable.js";
|
|
2
|
+
import { Option } from "../option/index.js";
|
|
3
|
+
import { Pipe } from "../pipe/index.js";
|
|
4
|
+
import { Serializable } from "../serializable/Serializable.js";
|
|
5
|
+
import { Typeable } from "../typeable/Typeable.js";
|
|
6
|
+
import { Type } from "../types/index.js";
|
|
7
|
+
import { List } from "./index.js";
|
|
8
|
+
/**
|
|
9
|
+
* LazyList provides lazy evaluation for list operations.
|
|
10
|
+
* Operations are deferred until the list is materialized.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // Basic lazy evaluation
|
|
14
|
+
* const result = LazyList([1, 2, 3, 4, 5])
|
|
15
|
+
* .map(x => x * 2)
|
|
16
|
+
* .filter(x => x > 5)
|
|
17
|
+
* .toArray() // [6, 8, 10]
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* // Infinite sequences with take
|
|
21
|
+
* const fibonacci = LazyList.iterate([0, 1], ([a, b]) => [b, a + b])
|
|
22
|
+
* .map(([a]) => a)
|
|
23
|
+
* .take(10)
|
|
24
|
+
* .toArray() // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
|
25
|
+
*/
|
|
26
|
+
export interface LazyList<out A extends Type> extends Foldable<A>, Pipe<LazyList<A>>, Serializable<LazyList<A>>, Typeable<"LazyList"> {
|
|
27
|
+
readonly [Symbol.toStringTag]: string;
|
|
28
|
+
[Symbol.iterator](): Iterator<A>;
|
|
29
|
+
map<B extends Type>(f: (a: A) => B): LazyList<B>;
|
|
30
|
+
flatMap<B extends Type>(f: (a: A) => LazyList<B>): LazyList<B>;
|
|
31
|
+
filter(predicate: (a: A) => boolean): LazyList<A>;
|
|
32
|
+
take(n: number): LazyList<A>;
|
|
33
|
+
drop(n: number): LazyList<A>;
|
|
34
|
+
takeWhile(predicate: (a: A) => boolean): LazyList<A>;
|
|
35
|
+
dropWhile(predicate: (a: A) => boolean): LazyList<A>;
|
|
36
|
+
/** Concatenate with another lazy list, possibly widening (Scala: `++[B >: A]`). */
|
|
37
|
+
concat<B extends Type>(other: LazyList<B>): LazyList<A | B>;
|
|
38
|
+
zip<B extends Type>(other: LazyList<B>): LazyList<[A, B]>;
|
|
39
|
+
takeRight(n: number): LazyList<A>;
|
|
40
|
+
reverse(): LazyList<A>;
|
|
41
|
+
distinct(): LazyList<A>;
|
|
42
|
+
zipWithIndex(): LazyList<[A, number]>;
|
|
43
|
+
head(): A | undefined;
|
|
44
|
+
headOption(): Option<A>;
|
|
45
|
+
last(): A | undefined;
|
|
46
|
+
lastOption(): Option<A>;
|
|
47
|
+
tail(): LazyList<A>;
|
|
48
|
+
init(): LazyList<A>;
|
|
49
|
+
fold<B>(initial: B, fn: (acc: B, a: A) => B): B;
|
|
50
|
+
toList(): List<A>;
|
|
51
|
+
toArray(): A[];
|
|
52
|
+
forEach(f: (a: A) => void): void;
|
|
53
|
+
reduce<B extends Type>(f: (acc: B, a: A) => B, initial: B): B;
|
|
54
|
+
find(predicate: (a: A) => boolean): Option<A>;
|
|
55
|
+
some(predicate: (a: A) => boolean): boolean;
|
|
56
|
+
every(predicate: (a: A) => boolean): boolean;
|
|
57
|
+
count(): number;
|
|
58
|
+
toString(): string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Create a LazyList from an iterable
|
|
62
|
+
* @example
|
|
63
|
+
* const lazy = LazyList([1, 2, 3, 4, 5])
|
|
64
|
+
* .map(x => x * x)
|
|
65
|
+
* .filter(x => x % 2 === 1)
|
|
66
|
+
* .toArray() // [1, 9, 25]
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* // From generator function
|
|
70
|
+
* function* naturals() {
|
|
71
|
+
* let n = 1
|
|
72
|
+
* while (true) yield n++
|
|
73
|
+
* }
|
|
74
|
+
* const firstTenSquares = LazyList(naturals())
|
|
75
|
+
* .map(x => x * x)
|
|
76
|
+
* .take(10)
|
|
77
|
+
* .toArray() // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
|
|
78
|
+
*/
|
|
79
|
+
declare const LazyListConstructor: <A extends Type>(iterable: Iterable<A>) => LazyList<A>;
|
|
80
|
+
declare const LazyListStatics: {
|
|
81
|
+
/**
|
|
82
|
+
* Create an empty LazyList
|
|
83
|
+
* @example
|
|
84
|
+
* const empty = LazyList.empty<number>()
|
|
85
|
+
* empty.toArray() // []
|
|
86
|
+
*/
|
|
87
|
+
empty: <A extends Type>() => LazyList<A>;
|
|
88
|
+
/**
|
|
89
|
+
* Create a LazyList from values (one or more)
|
|
90
|
+
* @example
|
|
91
|
+
* const single = LazyList.of(42)
|
|
92
|
+
* .map(x => x * 2)
|
|
93
|
+
* .toArray() // [84]
|
|
94
|
+
* LazyList.of(1, 2, 3).toArray() // [1, 2, 3], same as LazyList.from(1, 2, 3)
|
|
95
|
+
*/
|
|
96
|
+
of: <A extends Type>(...values: A[]) => LazyList<A>;
|
|
97
|
+
/**
|
|
98
|
+
* Create a LazyList from multiple values
|
|
99
|
+
*/
|
|
100
|
+
from: <A extends Type>(...values: A[]) => LazyList<A>;
|
|
101
|
+
/**
|
|
102
|
+
* Reconstruct a LazyList from a JSON envelope emitted by `serialize().toJSON()`
|
|
103
|
+
* or instance `toJSON()`. Verifies `@functype === "LazyList"` when the marker
|
|
104
|
+
* is present (canonical from 1.2.0). The materialized array becomes the new
|
|
105
|
+
* LazyList's backing — laziness can't survive JSON serialization.
|
|
106
|
+
*/
|
|
107
|
+
fromJSON: <A extends Type>(json: string) => LazyList<A>;
|
|
108
|
+
/**
|
|
109
|
+
* Create an infinite LazyList by repeatedly applying a function
|
|
110
|
+
* @example
|
|
111
|
+
* // Powers of 2
|
|
112
|
+
* const powers = LazyList.iterate(1, x => x * 2)
|
|
113
|
+
* .take(10)
|
|
114
|
+
* .toArray() // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* // Fibonacci sequence
|
|
118
|
+
* const fib = LazyList.iterate([0, 1], ([a, b]) => [b, a + b])
|
|
119
|
+
* .map(([a]) => a)
|
|
120
|
+
* .take(8)
|
|
121
|
+
* .toArray() // [0, 1, 1, 2, 3, 5, 8, 13]
|
|
122
|
+
*/
|
|
123
|
+
iterate: <A extends Type>(initial: A, f: (a: A) => A) => LazyList<A>;
|
|
124
|
+
/**
|
|
125
|
+
* Create an infinite LazyList by repeatedly calling a function
|
|
126
|
+
*/
|
|
127
|
+
generate: <A extends Type>(f: () => A) => LazyList<A>;
|
|
128
|
+
/**
|
|
129
|
+
* Create a LazyList of numbers from start to end (exclusive)
|
|
130
|
+
* @example
|
|
131
|
+
* LazyList.range(1, 6).toArray() // [1, 2, 3, 4, 5]
|
|
132
|
+
* LazyList.range(0, 10, 2).toArray() // [0, 2, 4, 6, 8]
|
|
133
|
+
* LazyList.range(10, 0, -1).toArray() // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* // Sum of squares from 1 to 100
|
|
137
|
+
* const sum = LazyList.range(1, 101)
|
|
138
|
+
* .map(x => x * x)
|
|
139
|
+
* .reduce((a, b) => a + b, 0) // 338350
|
|
140
|
+
*/
|
|
141
|
+
range: (start: number, end: number, step?: number) => LazyList<number>;
|
|
142
|
+
/**
|
|
143
|
+
* Create a LazyList that repeats a value n times (or infinitely if n is not provided)
|
|
144
|
+
*/
|
|
145
|
+
repeat: <A extends Type>(value: A, n?: number) => LazyList<A>;
|
|
146
|
+
/**
|
|
147
|
+
* Create a LazyList that cycles through an iterable infinitely
|
|
148
|
+
*/
|
|
149
|
+
cycle: <A extends Type>(iterable: Iterable<A>) => LazyList<A>;
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Lazy list implementation for efficient deferred computation
|
|
153
|
+
* @example
|
|
154
|
+
* // Process large datasets efficiently
|
|
155
|
+
* const result = LazyList.range(1, 1000000)
|
|
156
|
+
* .filter(x => x % 2 === 0)
|
|
157
|
+
* .map(x => x * x)
|
|
158
|
+
* .take(5)
|
|
159
|
+
* .toArray() // [4, 16, 36, 64, 100]
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* // Infinite sequences
|
|
163
|
+
* const primes = LazyList.iterate(2, n => n + 1)
|
|
164
|
+
* .filter(isPrime)
|
|
165
|
+
* .take(10)
|
|
166
|
+
* .toArray() // First 10 prime numbers
|
|
167
|
+
*
|
|
168
|
+
* @example
|
|
169
|
+
* // Combining operations
|
|
170
|
+
* const evens = LazyList.range(0, 100, 2)
|
|
171
|
+
* const odds = LazyList.range(1, 100, 2)
|
|
172
|
+
* const combined = evens.zip(odds)
|
|
173
|
+
* .map(([e, o]) => e + o)
|
|
174
|
+
* .take(5)
|
|
175
|
+
* .toArray() // [1, 5, 9, 13, 17]
|
|
176
|
+
*/
|
|
177
|
+
export declare const LazyList: LazyListCompanion;
|
|
178
|
+
/** The type of `LazyList`: its constructor and its statics, named so that errors and hovers print `LazyListCompanion`. */
|
|
179
|
+
export interface LazyListCompanion extends LazyListConstructorType, LazyListStaticsType {}
|
|
180
|
+
type LazyListConstructorType = typeof LazyListConstructor;
|
|
181
|
+
type LazyListStaticsType = typeof LazyListStatics;
|
|
182
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{define as t}from"../internal/define.js";import{Counter as n}from"../internal/mutation-utils.js";import{Option as r}from"../option/index.js";import{Ref as i}from"../ref/Ref.js";import{createSerializer as a}from"../serialization/SerializationCompanion.js";import{List as o}from"./index.js";const s=t()(`LazyList`,{[Symbol.toStringTag]:`LazyList`,[Symbol.iterator](){return this.source[Symbol.iterator]()},head(){let e=this.source[Symbol.iterator]().next();return e.done?void 0:e.value},headOption(){let e=this.source[Symbol.iterator]().next();return e.done?r.none():r(e.value)},last(){let e;for(let t of this.source)e=t;return e},lastOption(){let e=i(void 0),t=i(!1);for(let n of this.source)e.set(n),t.set(!0);return t.get()?r(e.get()):r.none()},tail(){let{source:e}=this;return c((function*(){let t=e[Symbol.iterator]();t.next();let n=t.next();for(;!n.done;)yield n.value,n=t.next()})())},init(){let e=Array.from(this.source);return c(e.length===0?[]:e.slice(0,-1))},map(e){let{source:t}=this;return c((function*(){for(let n of t)yield e(n)})())},flatMap(e){let{source:t}=this;return c((function*(){for(let n of t)yield*e(n)})())},filter(e){let{source:t}=this;return c((function*(){for(let n of t)e(n)&&(yield n)})())},take(e){let{source:t}=this;return c((function*(){let r=n(0);for(let n of t){if(!(r.get()<e))break;yield n,r.increment()}})())},drop(e){let{source:t}=this;return c((function*(){let r=n(0);for(let n of t)r.get()>=e&&(yield n),r.increment()})())},takeWhile(e){let{source:t}=this;return c((function*(){for(let n of t){if(!e(n))break;yield n}})())},dropWhile(e){let{source:t}=this;return c((function*(){let n=i(!0);for(let r of t)n.get()&&e(r)||(n.set(!1),yield r)})())},concat(e){let{source:t}=this;return c((function*(){yield*t,yield*e})())},zip(e){let{source:t}=this;return c((function*(){let n=t[Symbol.iterator](),r=e[Symbol.iterator]();for(;;){let e=n.next(),t=r.next();if(e.done||t.done)break;yield[e.value,t.value]}})())},toList(){return o(Array.from(this.source))},toArray(){return Array.from(this.source)},forEach(e){for(let t of this.source)e(t)},reduce(e,t){let n=i(t);for(let t of this.source)n.set(e(n.get(),t));return n.get()},find(e){for(let t of this.source)if(e(t))return r(t);return r.none()},some(e){for(let t of this.source)if(e(t))return!0;return!1},every(e){for(let t of this.source)if(!e(t))return!1;return!0},count(){let e=n(0);for(let t of this.source)e.increment();return e.get()},takeRight(e){let t=Array.from(this.source);return c(e>0?t.slice(-e):[])},reverse(){return c(Array.from(this.source).reverse())},distinct(){let{source:e}=this;return c((function*(){let t=new globalThis.Set;for(let n of e)t.has(n)||(t.add(n),yield n)})())},zipWithIndex(){let{source:e}=this;return c((function*(){let t=n(0);for(let n of e)yield[n,t.get()],t.increment()})())},fold(e,t){let n=e;for(let e of this.source)n=t(n,e);return n},foldLeft(e){return t=>{let n=i(e);for(let e of this.source)n.set(t(n.get(),e));return n.get()}},foldRight(e){return t=>Array.from(this.source).reduceRight((e,n)=>t(n,e),e)},pipe(e){return e(this)},serialize(){return a(`LazyList`,Array.from(this.source))},toJSON(){return{"@functype":`LazyList`,_tag:`LazyList`,value:Array.from(this.source)}},toString(){let e=[],t=n(0),r=i(!1);for(let n of this.source)if(t.get()<10)e.push(n),t.increment();else{r.set(!0);break}let a=e.map(e=>String(e)).join(`, `);return r.get()?`LazyList(${a}, ...)`:`LazyList(${a})`}}),c=e=>{let t=Object.create(s);return t._tag=`LazyList`,t.source=e,Object.freeze(t)},l=e(e=>c(e),{empty:()=>c([]),of:(...e)=>c(e),from:(...e)=>c(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`LazyList`)throw Error(`LazyList.fromJSON: expected @functype="LazyList", got ${JSON.stringify(t[`@functype`])}`);return c(t.value)},iterate:(e,t)=>c((function*(){let n=i(e);for(;;)yield n.get(),n.set(t(n.get()))})()),generate:e=>c((function*(){for(;;)yield e()})()),range:(e,t,n=1)=>c((function*(){if(n===0)throw Error(`Step cannot be zero`);let r=i(e);if(n>0)for(;r.get()<t;)yield r.get(),r.set(r.get()+n);else for(;r.get()>t;)yield r.get(),r.set(r.get()+n)})()),repeat:(e,t)=>c((function*(){if(t===void 0)for(;;)yield e;else{let r=n(0);for(;r.get()<t;)yield e,r.increment()}})()),cycle:e=>c((function*(){let t=Array.from(e);if(t.length!==0)for(;;)yield*t})())});export{l as LazyList};
|
package/dist/list/index.d.ts
CHANGED
|
@@ -1,2 +1,137 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Doable } from "../do/protocol.js";
|
|
2
|
+
import { FunctypeCollection } from "../functype/Functype.js";
|
|
3
|
+
import { ConcurrencyOptions } from "../internal/concurrency.js";
|
|
4
|
+
import { Option } from "../option/index.js";
|
|
5
|
+
import { Reshapeable } from "../reshapeable/Reshapeable.js";
|
|
6
|
+
import { Typeable } from "../typeable/Typeable.js";
|
|
7
|
+
import { Flattened } from "../typeclass/ContainerOps.js";
|
|
8
|
+
import { Type } from "../types/index.js";
|
|
9
|
+
/**
|
|
10
|
+
* Immutable List. Covariant in A (`<out A>`) — mirrors Scala's `List[+A]`.
|
|
11
|
+
*
|
|
12
|
+
* Methods that would otherwise force A-invariance use TS equivalents of Scala's
|
|
13
|
+
* co-variance patterns:
|
|
14
|
+
* - query/removal ops (`contains`, `indexOf`, `remove`) take `unknown`, matching
|
|
15
|
+
* Scala's `-(elem: Any)` / `contains(elem: Any)` — if the value can't possibly
|
|
16
|
+
* be in the list, it's a no-op, not a type error.
|
|
17
|
+
* - additive ops (`add`, `prepend`, `concat`) widen the element type, matching
|
|
18
|
+
* Scala's `::[B >: A]` / `++[B >: A]` — `List<A> + B` produces `List<A | B>`.
|
|
19
|
+
* - `reduce` / `reduceRight` accept a wider accumulator type, matching Scala's
|
|
20
|
+
* `reduce[B >: A]`.
|
|
21
|
+
*/
|
|
22
|
+
export interface List<out A> extends FunctypeCollection<A, "List">, Doable<A>, Reshapeable<A> {
|
|
23
|
+
readonly length: number;
|
|
24
|
+
[Symbol.iterator](): Iterator<A>;
|
|
25
|
+
map<B>(f: (a: A) => B): List<B>;
|
|
26
|
+
ap<B>(ff: List<(value: A) => B>): List<B>;
|
|
27
|
+
flatMap<B>(f: (a: A) => Iterable<B>): List<B>;
|
|
28
|
+
/** Async flatMap. Starts every call at once unless `options.concurrency` caps it; `{ concurrency: 1 }` runs them in order. */
|
|
29
|
+
flatMapAsync<B>(f: (a: A) => PromiseLike<Iterable<B>>, options?: ConcurrencyOptions): PromiseLike<List<B>>;
|
|
30
|
+
/**
|
|
31
|
+
* Async map: awaits `f` for each element and keeps the results in input order.
|
|
32
|
+
*
|
|
33
|
+
* Runs one call at a time by default, which is what replacing a loop that awaits needs. Pass
|
|
34
|
+
* `{ concurrency: n }` to allow up to `n` calls at once, or `"unbounded"` to start them all together.
|
|
35
|
+
* (`flatMapAsync` defaults to `"unbounded"`; it keeps that default so existing callers don't change.)
|
|
36
|
+
* A rejection rejects the result, and no further calls start.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* const users = await List(ids).mapAsync(fetchUser) // in order, one at a time
|
|
41
|
+
* const pages = await List(urls).mapAsync(fetchPage, { concurrency: 4 }) // up to 4 at once
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
mapAsync<B>(f: (a: A) => PromiseLike<B>, options?: ConcurrencyOptions): Promise<List<B>>;
|
|
45
|
+
filter<S extends A>(predicate: (a: A) => a is S): List<S>;
|
|
46
|
+
filter(predicate: (a: A) => unknown): List<A>;
|
|
47
|
+
filterNot(p: (a: A) => boolean): List<A>;
|
|
48
|
+
/** @internal */
|
|
49
|
+
filterType<T extends Typeable<string, unknown>>(tag: string): List<T & A>;
|
|
50
|
+
/** Remove a value. Accepts `unknown` so an unrelated-type arg is a safe no-op (Scala: `-(elem: Any)`). */
|
|
51
|
+
remove(value: unknown): List<A>;
|
|
52
|
+
removeAt(index: number): List<A>;
|
|
53
|
+
/** Add a value, possibly widening the element type (Scala: `:+[B >: A]`). */
|
|
54
|
+
add<B>(item: B): List<A | B>;
|
|
55
|
+
get(index: number): Option<A>;
|
|
56
|
+
/** Concatenate with another list, possibly widening (Scala: `++[B >: A]`). */
|
|
57
|
+
concat<B>(other: List<B>): List<A | B>;
|
|
58
|
+
take(n: number): List<A>;
|
|
59
|
+
takeWhile(p: (a: A) => boolean): List<A>;
|
|
60
|
+
takeRight(n: number): List<A>;
|
|
61
|
+
/** Drop the first `n` elements. `n` of 0 or less drops nothing. */
|
|
62
|
+
drop(n: number): List<A>;
|
|
63
|
+
/** Drop the last `n` elements. `n` of 0 or less drops nothing. */
|
|
64
|
+
dropRight(n: number): List<A>;
|
|
65
|
+
/** Drop elements while `p` holds. Gives an empty List when every element matches. */
|
|
66
|
+
dropWhile(p: (a: A) => boolean): List<A>;
|
|
67
|
+
/**
|
|
68
|
+
* Spread each element that's an array or another non-string iterable (List, Set, ...) into the result,
|
|
69
|
+
* one level deep, keeping other elements, strings included, as they are.
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* List([[1, 2], [3]]).flatten() // List([1, 2, 3])
|
|
73
|
+
* List([List([1]), List([2])]).flatten() // List([1, 2])
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
flatten<B = Flattened<A>>(): List<B>;
|
|
77
|
+
last(): A | undefined;
|
|
78
|
+
lastOption(): Option<A>;
|
|
79
|
+
tail(): List<A>;
|
|
80
|
+
init(): List<A>;
|
|
81
|
+
reverse(): List<A>;
|
|
82
|
+
/** Find the index of a value. Accepts `unknown` (Scala: `indexOf(elem: Any)`). */
|
|
83
|
+
indexOf(value: unknown): number;
|
|
84
|
+
/** Prepend a value, possibly widening (Scala: `+:[B >: A]`). */
|
|
85
|
+
prepend<B>(item: B): List<A | B>;
|
|
86
|
+
distinct(): List<A>;
|
|
87
|
+
sorted(compareFn?: (a: A, b: A) => number): List<A>;
|
|
88
|
+
sortBy<B>(f: (a: A) => B, compareFn?: (a: B, b: B) => number): List<A>;
|
|
89
|
+
zip<B>(other: List<B>): List<[A, B]>;
|
|
90
|
+
zipWithIndex(): List<[A, number]>;
|
|
91
|
+
groupBy<K>(f: (a: A) => K): globalThis.Map<K, List<A>>;
|
|
92
|
+
partition(p: (a: A) => boolean): [List<A>, List<A>];
|
|
93
|
+
span(p: (a: A) => boolean): [List<A>, List<A>];
|
|
94
|
+
slice(start: number, end: number): List<A>;
|
|
95
|
+
/**
|
|
96
|
+
* Pattern matches over the List, applying a handler function based on whether it's empty
|
|
97
|
+
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
98
|
+
* @returns The result of applying the matching handler function
|
|
99
|
+
*/
|
|
100
|
+
match<R>(patterns: {
|
|
101
|
+
Empty: () => R;
|
|
102
|
+
NonEmpty: (values: A[]) => R;
|
|
103
|
+
}): R;
|
|
104
|
+
}
|
|
105
|
+
declare const ListConstructor: <A>(values?: Iterable<A>) => List<A>;
|
|
106
|
+
declare const ListStatics: {
|
|
107
|
+
/**
|
|
108
|
+
* Creates an empty List
|
|
109
|
+
* Returns one shared instance, whose backing array is frozen
|
|
110
|
+
* @returns An empty List instance
|
|
111
|
+
*/
|
|
112
|
+
empty: <A extends Type>() => List<A>;
|
|
113
|
+
/**
|
|
114
|
+
* Creates a List from variadic arguments
|
|
115
|
+
* @param values - Values to create list from
|
|
116
|
+
* @returns A List containing the values
|
|
117
|
+
*/
|
|
118
|
+
of: <A extends Type>(...values: A[]) => List<A>;
|
|
119
|
+
/**
|
|
120
|
+
* Creates a List from JSON string
|
|
121
|
+
* @param json - The JSON string
|
|
122
|
+
* @returns List instance
|
|
123
|
+
*/
|
|
124
|
+
fromJSON: <A>(json: string) => List<A>;
|
|
125
|
+
/**
|
|
126
|
+
* Creates a List from binary string
|
|
127
|
+
* @param binary - The binary string
|
|
128
|
+
* @returns List instance
|
|
129
|
+
*/
|
|
130
|
+
fromBinary: <A>(binary: string) => List<A>;
|
|
131
|
+
};
|
|
132
|
+
export declare const List: ListCompanion;
|
|
133
|
+
/** The type of `List`: its constructor and its statics, named so that errors and hovers print `ListCompanion`. */
|
|
134
|
+
export interface ListCompanion extends ListConstructorType, ListStaticsType {}
|
|
135
|
+
type ListConstructorType = typeof ListConstructor;
|
|
136
|
+
type ListStaticsType = typeof ListStatics;
|
|
137
|
+
export {};
|