@carbonteq/fp 0.9.1 → 0.10.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 +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +286 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1266 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +46 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +237 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +241 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +50 -18
package/dist/option.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { UNIT } from "./unit.mjs";
|
|
2
|
-
import { isPromiseLike } from "./utils.mjs";
|
|
2
|
+
import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
|
|
3
3
|
import { Result } from "./result.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/option.ts
|
|
@@ -11,11 +11,51 @@ var UnwrappedNone = class extends Error {
|
|
|
11
11
|
};
|
|
12
12
|
const UNWRAPPED_NONE_ERR = new UnwrappedNone();
|
|
13
13
|
const NONE_VAL = Symbol("Option::None");
|
|
14
|
+
/**
|
|
15
|
+
* Wrapper that makes Option yieldable with proper type tracking.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
var OptionYieldWrap = class {
|
|
20
|
+
constructor(option) {
|
|
21
|
+
this.option = option;
|
|
22
|
+
}
|
|
23
|
+
*[Symbol.iterator]() {
|
|
24
|
+
return yield this;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Wrapper that makes Option yieldable in async generators with proper type tracking.
|
|
29
|
+
*
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
var AsyncOptionYieldWrap = class {
|
|
33
|
+
option;
|
|
34
|
+
constructor(option) {
|
|
35
|
+
this.option = isPromiseLike(option) ? option : Promise.resolve(option);
|
|
36
|
+
}
|
|
37
|
+
async *[Symbol.asyncIterator]() {
|
|
38
|
+
return yield this;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Represents an optional value: `Some<T>` or `None`.
|
|
43
|
+
* Provides composable, null-safe transformation and chaining methods.
|
|
44
|
+
*/
|
|
14
45
|
var Option = class Option {
|
|
15
46
|
/** Discriminant tag for type-level identification */
|
|
16
47
|
_tag;
|
|
17
48
|
#ctx;
|
|
18
49
|
#val;
|
|
50
|
+
/**
|
|
51
|
+
* Creates a new Option instance with internal context.
|
|
52
|
+
*
|
|
53
|
+
* @param val - Stored value or sentinel
|
|
54
|
+
* @param ctx - Internal async tracking context
|
|
55
|
+
* @param tag - Discriminant tag for Some/None
|
|
56
|
+
*
|
|
57
|
+
* @internal
|
|
58
|
+
*/
|
|
19
59
|
constructor(val, ctx, tag) {
|
|
20
60
|
this.#val = val;
|
|
21
61
|
this.#ctx = ctx;
|
|
@@ -23,23 +63,60 @@ var Option = class Option {
|
|
|
23
63
|
}
|
|
24
64
|
/** Singleton None instance */
|
|
25
65
|
static None = new Option(NONE_VAL, { promiseNoneSlot: true }, "None");
|
|
26
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Creates a Some variant containing the provided value.
|
|
68
|
+
*
|
|
69
|
+
* @template Inner - Type of the wrapped value
|
|
70
|
+
* @param val - Value to wrap in Some
|
|
71
|
+
* @returns Option in the Some state
|
|
72
|
+
*/
|
|
27
73
|
static Some(val) {
|
|
28
74
|
return new Option(val, { promiseNoneSlot: false }, "Some");
|
|
29
75
|
}
|
|
30
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* Creates an Option from a nullable value, returning None for null/undefined.
|
|
78
|
+
*
|
|
79
|
+
* @template T - Input type that may include null/undefined
|
|
80
|
+
* @param val - Value to convert
|
|
81
|
+
* @returns Some for non-nullish values, otherwise None
|
|
82
|
+
*/
|
|
31
83
|
static fromNullable(val) {
|
|
32
84
|
return val === null || val === void 0 ? Option.None : Option.Some(val);
|
|
33
85
|
}
|
|
34
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Creates an Option from a potentially falsy value, returning None for falsy.
|
|
88
|
+
*
|
|
89
|
+
* Treats false, 0, "", null, and undefined as absence.
|
|
90
|
+
*
|
|
91
|
+
* @template T - Input type
|
|
92
|
+
* @param val - Value to convert
|
|
93
|
+
* @returns Some for truthy values, otherwise None
|
|
94
|
+
*/
|
|
35
95
|
static fromFalsy(val) {
|
|
36
96
|
return val ? Option.Some(val) : Option.None;
|
|
37
97
|
}
|
|
38
|
-
/**
|
|
98
|
+
/**
|
|
99
|
+
* Creates an Option based on a predicate.
|
|
100
|
+
*
|
|
101
|
+
* @template T - Input type
|
|
102
|
+
* @param val - Value to test
|
|
103
|
+
* @param pred - Predicate to decide Some vs None
|
|
104
|
+
* @returns Some when predicate passes, otherwise None
|
|
105
|
+
*/
|
|
39
106
|
static fromPredicate(val, pred) {
|
|
40
107
|
return pred(val) ? Option.Some(val) : Option.None;
|
|
41
108
|
}
|
|
42
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Wraps a Promise<Option<T>> as Option<Promise<T>>.
|
|
111
|
+
*
|
|
112
|
+
* NOTE: the returned value starts as `Some(Promise<T>)`; final `None` is known
|
|
113
|
+
* only after settlement. Use `toPromise()` (or await `unwrap`/`safeUnwrap`) to
|
|
114
|
+
* observe settled absence.
|
|
115
|
+
*
|
|
116
|
+
* @template U - Inner value type
|
|
117
|
+
* @param o - Promise resolving to an Option
|
|
118
|
+
* @returns Option containing a Promise of the inner value
|
|
119
|
+
*/
|
|
43
120
|
static fromPromise(o) {
|
|
44
121
|
const ctx = { promiseNoneSlot: false };
|
|
45
122
|
return new Option(new Promise((resolve, reject) => o.then((innerOpt) => {
|
|
@@ -47,7 +124,15 @@ var Option = class Option {
|
|
|
47
124
|
resolve(innerOpt.#val);
|
|
48
125
|
}, reject)), ctx, "Some");
|
|
49
126
|
}
|
|
50
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* Combines multiple Options into a single Option of an array.
|
|
129
|
+
*
|
|
130
|
+
* Returns Some of all values if all inputs are Some; otherwise None.
|
|
131
|
+
*
|
|
132
|
+
* @template T - Variadic tuple of Option types
|
|
133
|
+
* @param options - Options to combine
|
|
134
|
+
* @returns Some of tuple values, or None if any input is None
|
|
135
|
+
*/
|
|
51
136
|
static all(...options) {
|
|
52
137
|
const vals = [];
|
|
53
138
|
for (const opt of options) {
|
|
@@ -56,44 +141,112 @@ var Option = class Option {
|
|
|
56
141
|
}
|
|
57
142
|
return Option.Some(vals);
|
|
58
143
|
}
|
|
59
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* Returns the first Some in the list, or None if all are None.
|
|
146
|
+
*
|
|
147
|
+
* For async Some values, settlement is awaited and selection follows input order.
|
|
148
|
+
*
|
|
149
|
+
* @template T - Value type
|
|
150
|
+
* @param options - Options to search
|
|
151
|
+
* @returns The first Some found, otherwise None
|
|
152
|
+
*/
|
|
60
153
|
static any(...options) {
|
|
61
|
-
|
|
62
|
-
|
|
154
|
+
const pending = [];
|
|
155
|
+
for (const opt of options) if (opt.isSome()) {
|
|
156
|
+
if (isPromiseLike(opt.#val)) {
|
|
157
|
+
pending.push(opt);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
return opt;
|
|
161
|
+
}
|
|
162
|
+
if (pending.length === 0) return Option.None;
|
|
163
|
+
const ctx = { promiseNoneSlot: false };
|
|
164
|
+
return new Option(Promise.all(pending.map(async (opt) => {
|
|
165
|
+
const val = await opt.#val;
|
|
166
|
+
return {
|
|
167
|
+
isNone: opt.#ctx.promiseNoneSlot || val === NONE_VAL,
|
|
168
|
+
val
|
|
169
|
+
};
|
|
170
|
+
})).then((settled) => {
|
|
171
|
+
for (const item of settled) if (!item.isNone) return item.val;
|
|
172
|
+
ctx.promiseNoneSlot = true;
|
|
173
|
+
return NONE_VAL;
|
|
174
|
+
}), ctx, "Some");
|
|
63
175
|
}
|
|
64
|
-
/**
|
|
176
|
+
/**
|
|
177
|
+
* Type guard that narrows to Some.
|
|
178
|
+
*
|
|
179
|
+
* @returns true if this Option is Some
|
|
180
|
+
*/
|
|
65
181
|
isSome() {
|
|
66
182
|
return this._tag === "Some" && !this.isNone();
|
|
67
183
|
}
|
|
68
|
-
/**
|
|
184
|
+
/**
|
|
185
|
+
* Type guard that narrows to None.
|
|
186
|
+
*
|
|
187
|
+
* Includes async None tracking for Option<Promise<T>>.
|
|
188
|
+
*
|
|
189
|
+
* @returns true if this Option is None
|
|
190
|
+
*/
|
|
69
191
|
isNone() {
|
|
70
192
|
return this._tag === "None" || this.#val === NONE_VAL || isPromiseLike(this.#val) && this.#ctx.promiseNoneSlot;
|
|
71
193
|
}
|
|
72
|
-
/**
|
|
194
|
+
/**
|
|
195
|
+
* Type guard for the UNIT sentinel value.
|
|
196
|
+
*
|
|
197
|
+
* @returns true if the contained value is UNIT
|
|
198
|
+
*/
|
|
73
199
|
isUnit() {
|
|
74
200
|
return this.#val === UNIT;
|
|
75
201
|
}
|
|
76
|
-
/** Returns value or throws UnwrapError */
|
|
77
202
|
unwrap() {
|
|
78
203
|
if (this.isNone()) throw UNWRAPPED_NONE_ERR;
|
|
79
|
-
|
|
204
|
+
const curr = this.#val;
|
|
205
|
+
if (isPromiseLike(curr)) {
|
|
206
|
+
const ctx = this.#ctx;
|
|
207
|
+
return curr.then((value) => {
|
|
208
|
+
if (value === NONE_VAL || ctx.promiseNoneSlot) throw UNWRAPPED_NONE_ERR;
|
|
209
|
+
return value;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return curr;
|
|
80
213
|
}
|
|
81
|
-
/**
|
|
214
|
+
/**
|
|
215
|
+
* Returns the contained value or the provided default.
|
|
216
|
+
*
|
|
217
|
+
* @param defaultValue - Value to use when None
|
|
218
|
+
* @returns The contained value or default
|
|
219
|
+
*/
|
|
82
220
|
unwrapOr(defaultValue) {
|
|
83
221
|
if (this.isNone()) return defaultValue;
|
|
84
222
|
return this.#val;
|
|
85
223
|
}
|
|
86
|
-
/**
|
|
224
|
+
/**
|
|
225
|
+
* Returns the contained value or computes a default lazily.
|
|
226
|
+
*
|
|
227
|
+
* @param fn - Default factory invoked only when None
|
|
228
|
+
* @returns The contained value or computed default
|
|
229
|
+
*/
|
|
87
230
|
unwrapOrElse(fn) {
|
|
88
231
|
if (this.isNone()) return fn();
|
|
89
232
|
return this.#val;
|
|
90
233
|
}
|
|
91
|
-
/** Returns value or null for None */
|
|
92
234
|
safeUnwrap() {
|
|
93
235
|
if (this.isNone()) return null;
|
|
94
|
-
|
|
236
|
+
const curr = this.#val;
|
|
237
|
+
if (isPromiseLike(curr)) {
|
|
238
|
+
const ctx = this.#ctx;
|
|
239
|
+
return curr.then((value) => value === NONE_VAL || ctx.promiseNoneSlot ? null : value);
|
|
240
|
+
}
|
|
241
|
+
return curr;
|
|
95
242
|
}
|
|
96
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Exhaustive pattern match on Option state.
|
|
245
|
+
*
|
|
246
|
+
* @template U - Result type
|
|
247
|
+
* @param cases - Handlers for Some and None
|
|
248
|
+
* @returns Result of the matching handler
|
|
249
|
+
*/
|
|
97
250
|
match(cases) {
|
|
98
251
|
if (this.isNone()) return cases.None();
|
|
99
252
|
return cases.Some(this.#val);
|
|
@@ -110,6 +263,16 @@ var Option = class Option {
|
|
|
110
263
|
if (isPromiseLike(transformed)) return new Option(transformed, { promiseNoneSlot: false }, "Some");
|
|
111
264
|
return new Option(transformed, { promiseNoneSlot: false }, "Some");
|
|
112
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Safely maps a promised value while tracking None in async context.
|
|
268
|
+
*
|
|
269
|
+
* @template Curr - Input value type
|
|
270
|
+
* @template U - Output value type
|
|
271
|
+
* @param p - Promise to map over
|
|
272
|
+
* @param mapper - Transform function
|
|
273
|
+
* @param ctx - Async context for None tracking
|
|
274
|
+
* @returns Promise of the transformed value or sentinel
|
|
275
|
+
*/
|
|
113
276
|
static safeMap(p, mapper, ctx) {
|
|
114
277
|
return p.then((v) => {
|
|
115
278
|
if (v === NONE_VAL) {
|
|
@@ -122,10 +285,14 @@ var Option = class Option {
|
|
|
122
285
|
mapOr(defaultVal, fn) {
|
|
123
286
|
if (this.isNone()) return isPromiseLike(this.#val) ? Promise.resolve(defaultVal) : defaultVal;
|
|
124
287
|
const curr = this.#val;
|
|
125
|
-
if (isPromiseLike(curr))
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
288
|
+
if (isPromiseLike(curr)) {
|
|
289
|
+
const p = curr;
|
|
290
|
+
const ctx = this.#ctx;
|
|
291
|
+
return p.then(async (v) => {
|
|
292
|
+
if (v === NONE_VAL || ctx.promiseNoneSlot) return defaultVal;
|
|
293
|
+
return fn(v);
|
|
294
|
+
});
|
|
295
|
+
}
|
|
129
296
|
return fn(curr);
|
|
130
297
|
}
|
|
131
298
|
flatMap(mapper) {
|
|
@@ -239,39 +406,398 @@ var Option = class Option {
|
|
|
239
406
|
}
|
|
240
407
|
return u.map((inner) => [c, inner]);
|
|
241
408
|
}
|
|
242
|
-
/**
|
|
409
|
+
/**
|
|
410
|
+
* Executes a side effect for Some values and returns self.
|
|
411
|
+
*
|
|
412
|
+
* For `Option<Promise<T>>`, `tap` receives the wrapped promise object,
|
|
413
|
+
* not the settled inner value.
|
|
414
|
+
*
|
|
415
|
+
* @param fn - Side effect function
|
|
416
|
+
* @returns The same Option (chainable)
|
|
417
|
+
*/
|
|
243
418
|
tap(fn) {
|
|
244
419
|
if (this.isSome()) fn(this.#val);
|
|
245
420
|
return this;
|
|
246
421
|
}
|
|
247
|
-
/**
|
|
422
|
+
/**
|
|
423
|
+
* Converts this Option to a Result, using the provided error for None.
|
|
424
|
+
*
|
|
425
|
+
* @template E - Error type
|
|
426
|
+
* @param error - Error value for None
|
|
427
|
+
* @returns Ok with value when Some, otherwise Err with error
|
|
428
|
+
*/
|
|
248
429
|
toResult(error) {
|
|
249
430
|
if (this.isNone()) return Result.Err(error);
|
|
250
431
|
return Result.Ok(this.#val);
|
|
251
432
|
}
|
|
252
|
-
/**
|
|
433
|
+
/**
|
|
434
|
+
* Resolves the inner promise (if any) while preserving Option structure.
|
|
435
|
+
*
|
|
436
|
+
* @template Curr - Awaited value type
|
|
437
|
+
* @returns Promise of Option with awaited value, or None
|
|
438
|
+
*/
|
|
253
439
|
async toPromise() {
|
|
254
440
|
if (this.isNone()) return Option.None;
|
|
255
441
|
const curr = this.#val;
|
|
256
442
|
let inner;
|
|
257
443
|
if (isPromiseLike(curr)) {
|
|
258
444
|
const awaited = await curr;
|
|
259
|
-
if (awaited === NONE_VAL) return Option.None;
|
|
445
|
+
if (awaited === NONE_VAL || this.#ctx.promiseNoneSlot) return Option.None;
|
|
260
446
|
inner = awaited;
|
|
261
447
|
} else inner = curr;
|
|
262
448
|
return new Option(inner, this.#ctx, "Some");
|
|
263
449
|
}
|
|
264
|
-
/**
|
|
450
|
+
/**
|
|
451
|
+
* Maps over array elements inside an Option<Array<T>>.
|
|
452
|
+
*
|
|
453
|
+
* @template Inner - Array element type
|
|
454
|
+
* @template Out - Mapped element type
|
|
455
|
+
* @param mapper - Function to map each element
|
|
456
|
+
* @returns Option containing the mapped array
|
|
457
|
+
* @throws TypeError if called on a non-array value
|
|
458
|
+
*/
|
|
265
459
|
innerMap(mapper) {
|
|
266
460
|
if (this.isNone()) return Option.None;
|
|
267
461
|
if (!Array.isArray(this.#val)) throw new TypeError("innerMap can only be called on Option<Array<T>>");
|
|
268
462
|
return new Option(this.#val.map(mapper), this.#ctx, "Some");
|
|
269
463
|
}
|
|
270
|
-
/**
|
|
464
|
+
/**
|
|
465
|
+
* Returns a string representation of the Option.
|
|
466
|
+
*
|
|
467
|
+
* @returns "Option::None" or "Option::Some(value)"
|
|
468
|
+
*/
|
|
271
469
|
toString() {
|
|
272
470
|
if (this.isNone()) return "Option::None";
|
|
273
471
|
return `Option::Some(${String(this.#val)})`;
|
|
274
472
|
}
|
|
473
|
+
/**
|
|
474
|
+
* Makes Option iterable for use with generator-based syntax.
|
|
475
|
+
*
|
|
476
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
477
|
+
* Used internally by {@link Option.gen} for `yield*` syntax.
|
|
478
|
+
*
|
|
479
|
+
* @example
|
|
480
|
+
* ```ts
|
|
481
|
+
* const result = Option.gen(function* () {
|
|
482
|
+
* const value = yield* Option.Some(42);
|
|
483
|
+
* return value * 2;
|
|
484
|
+
* });
|
|
485
|
+
* // Some(84)
|
|
486
|
+
* ```
|
|
487
|
+
*
|
|
488
|
+
* @internal
|
|
489
|
+
*/
|
|
490
|
+
*[Symbol.iterator]() {
|
|
491
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
492
|
+
return yield new CapturedTrace(this, trace);
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Makes Option iterable for use with async generator-based syntax.
|
|
496
|
+
*
|
|
497
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
498
|
+
* Used internally by {@link Option.asyncGen} for `yield*` syntax.
|
|
499
|
+
*
|
|
500
|
+
* @example
|
|
501
|
+
* ```ts
|
|
502
|
+
* const result = await Option.asyncGen(async function* () {
|
|
503
|
+
* const value = yield* await Promise.resolve(Option.Some(42));
|
|
504
|
+
* return value * 2;
|
|
505
|
+
* });
|
|
506
|
+
* // Some(84)
|
|
507
|
+
* ```
|
|
508
|
+
*
|
|
509
|
+
* @internal
|
|
510
|
+
*/
|
|
511
|
+
async *[Symbol.asyncIterator]() {
|
|
512
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
513
|
+
return yield new CapturedTrace(this, trace);
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Generator-based syntax for chaining Option operations (simplified, no adapter).
|
|
517
|
+
*
|
|
518
|
+
* Provides imperative-style code while maintaining functional Option handling.
|
|
519
|
+
* Use `yield*` to unwrap Options or short-circuit on `None`.
|
|
520
|
+
*
|
|
521
|
+
* Short-circuits on first `None`, returning singleton `None`. Uses iteration
|
|
522
|
+
* instead of recursion to avoid stack overflow on deep chains.
|
|
523
|
+
*
|
|
524
|
+
* @template T - The return type of the generator
|
|
525
|
+
* @param genFn - A generator function that yields Options
|
|
526
|
+
* @returns `Some<T>` with the generator's return value, or `None`
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* ```ts
|
|
530
|
+
* // Simple sync chain
|
|
531
|
+
* const result = Option.gen(function* () {
|
|
532
|
+
* const a = yield* Option.Some(1);
|
|
533
|
+
* const b = yield* Option.Some(2);
|
|
534
|
+
* return a + b;
|
|
535
|
+
* });
|
|
536
|
+
* // Some(3)
|
|
537
|
+
*
|
|
538
|
+
* // None short-circuit
|
|
539
|
+
* const shortCircuit = Option.gen(function* () {
|
|
540
|
+
* const a = yield* Option.Some(1);
|
|
541
|
+
* const b = yield* Option.None; // Short-circuits here
|
|
542
|
+
* const c = yield* Option.Some(3); // Never executes
|
|
543
|
+
* return a + b + c;
|
|
544
|
+
* });
|
|
545
|
+
* // None
|
|
546
|
+
*
|
|
547
|
+
* // Chaining optional operations
|
|
548
|
+
* const email = Option.gen(function* () {
|
|
549
|
+
* const user = yield* findUser(userId);
|
|
550
|
+
* const profile = yield* Option.fromNullable(user.profile);
|
|
551
|
+
* const settings = yield* Option.fromNullable(profile.settings);
|
|
552
|
+
* return settings.email;
|
|
553
|
+
* });
|
|
554
|
+
*
|
|
555
|
+
* // Nested optional access
|
|
556
|
+
* const city = Option.gen(function* () {
|
|
557
|
+
* const user = yield* Option.fromNullable(getUser());
|
|
558
|
+
* const address = yield* Option.fromNullable(user?.address);
|
|
559
|
+
* const city = yield* Option.fromNullable(address?.city);
|
|
560
|
+
* return city;
|
|
561
|
+
* });
|
|
562
|
+
* ```
|
|
563
|
+
*
|
|
564
|
+
* @see {@link genAdapter} for better type inference in complex chains
|
|
565
|
+
* @see {@link asyncGen} for async operations
|
|
566
|
+
*/
|
|
567
|
+
static gen(genFn) {
|
|
568
|
+
const iterator = genFn();
|
|
569
|
+
let nextArg;
|
|
570
|
+
let currentResult;
|
|
571
|
+
while (true) {
|
|
572
|
+
const next = iterator.next(nextArg);
|
|
573
|
+
if (next.done) {
|
|
574
|
+
currentResult = Option.Some(next.value);
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
let yielded = next.value;
|
|
578
|
+
if (isCapturedTrace(yielded)) yielded = yielded.value;
|
|
579
|
+
if (yielded.isNone()) {
|
|
580
|
+
currentResult = Option.None;
|
|
581
|
+
break;
|
|
582
|
+
}
|
|
583
|
+
nextArg = yielded.unwrap();
|
|
584
|
+
}
|
|
585
|
+
return currentResult;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Generator-based syntax for chaining Option operations with an adapter function.
|
|
589
|
+
*
|
|
590
|
+
* Provides better type inference and IDE support compared to {@link gen}.
|
|
591
|
+
* The `$` adapter wraps Options and enables clearer type tracking.
|
|
592
|
+
*
|
|
593
|
+
* Short-circuits on first `None`, returning singleton `None`. Uses iteration
|
|
594
|
+
* instead of recursion to avoid stack overflow on deep chains.
|
|
595
|
+
*
|
|
596
|
+
* @template Eff - The effect type (inferred from usage)
|
|
597
|
+
* @template T - The return type of the generator
|
|
598
|
+
* @param genFn - A generator function receiving an adapter `$`
|
|
599
|
+
* @returns `Some<T>` with the generator's return value, or `None`
|
|
600
|
+
*
|
|
601
|
+
* @example
|
|
602
|
+
* ```ts
|
|
603
|
+
* // Better type inference
|
|
604
|
+
* const result = Option.genAdapter(function* ($) {
|
|
605
|
+
* const a = yield* $(Option.Some(1));
|
|
606
|
+
* const b = yield* $(Option.Some(2));
|
|
607
|
+
* return a + b;
|
|
608
|
+
* });
|
|
609
|
+
* // Some(3)
|
|
610
|
+
*
|
|
611
|
+
* // Deep nested access with better type safety
|
|
612
|
+
* const email = Option.genAdapter(function* ($) {
|
|
613
|
+
* const user = yield* $(Option.fromNullable(apiResponse?.user));
|
|
614
|
+
* const profile = yield* $(Option.fromNullable(user?.profile));
|
|
615
|
+
* const contact = yield* $(Option.fromNullable(profile?.contact));
|
|
616
|
+
* return contact?.email;
|
|
617
|
+
* });
|
|
618
|
+
*
|
|
619
|
+
* // Complex validation chain
|
|
620
|
+
* const validConfig = Option.genAdapter(function* ($) {
|
|
621
|
+
* const raw = yield* $(loadConfig());
|
|
622
|
+
* const parsed = yield* $(parseConfig(raw));
|
|
623
|
+
* const validated = yield* $(validateConfig(parsed));
|
|
624
|
+
* return validated;
|
|
625
|
+
* });
|
|
626
|
+
* ```
|
|
627
|
+
*
|
|
628
|
+
* @see {@link gen} for simpler chains without adapter
|
|
629
|
+
* @see {@link asyncGenAdapter} for async operations
|
|
630
|
+
*/
|
|
631
|
+
static genAdapter(genFn) {
|
|
632
|
+
const adapter = (option) => new OptionYieldWrap(option);
|
|
633
|
+
const iterator = genFn(adapter);
|
|
634
|
+
let nextArg;
|
|
635
|
+
let currentResult;
|
|
636
|
+
while (true) {
|
|
637
|
+
const next = iterator.next(nextArg);
|
|
638
|
+
if (next.done) {
|
|
639
|
+
currentResult = Option.Some(next.value);
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
let option = next.value.option;
|
|
643
|
+
if (isCapturedTrace(option)) option = option.value;
|
|
644
|
+
if (option.isNone()) {
|
|
645
|
+
currentResult = Option.None;
|
|
646
|
+
break;
|
|
647
|
+
}
|
|
648
|
+
nextArg = option.unwrap();
|
|
649
|
+
}
|
|
650
|
+
return currentResult;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Async generator-based syntax for chaining Option operations (simplified, no adapter).
|
|
654
|
+
*
|
|
655
|
+
* Use `yield*` with `Option<T>` values directly. For `Promise<Option<T>>`,
|
|
656
|
+
* await first then `yield*`.
|
|
657
|
+
*
|
|
658
|
+
* Short-circuits on first `None`, returning singleton `None`. Uses async iteration
|
|
659
|
+
* instead of recursion to avoid stack overflow on deep chains.
|
|
660
|
+
*
|
|
661
|
+
* @template T - The return type of the generator
|
|
662
|
+
* @param genFn - An async generator function that yields Options
|
|
663
|
+
* @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* ```ts
|
|
667
|
+
* // Simple async chain
|
|
668
|
+
* const result = await Option.asyncGen(async function* () {
|
|
669
|
+
* const a = yield* Option.Some(1);
|
|
670
|
+
* const b = yield* await asyncOperation(a); // await Promise<Option> first
|
|
671
|
+
* const c = yield* Option.Some(3);
|
|
672
|
+
* return a + b + c;
|
|
673
|
+
* });
|
|
674
|
+
* // Some(result)
|
|
675
|
+
*
|
|
676
|
+
* // None short-circuit in async
|
|
677
|
+
* const shortCircuit = await Option.asyncGen(async function* () {
|
|
678
|
+
* const data = yield* await fetchOptionalData();
|
|
679
|
+
* const parsed = yield* parse(data); // Short-circuits on None
|
|
680
|
+
* const validated = yield* validate(parsed); // Never executes
|
|
681
|
+
* return validated;
|
|
682
|
+
* });
|
|
683
|
+
* // None
|
|
684
|
+
*
|
|
685
|
+
* // Mixed sync/async workflow
|
|
686
|
+
* const result = await Option.asyncGen(async function* () {
|
|
687
|
+
* const id = yield* Option.Some(parseInt(input)); // sync
|
|
688
|
+
* const user = yield* await fetchUser(id); // async
|
|
689
|
+
* const profile = yield* Option.fromNullable(user?.profile); // sync
|
|
690
|
+
* const enriched = yield* await enrichProfile(profile); // async
|
|
691
|
+
* return enriched;
|
|
692
|
+
* });
|
|
693
|
+
*
|
|
694
|
+
* // Complex pipeline with multiple optional steps
|
|
695
|
+
* async function processLead(email: string): Promise<Option<Lead>> {
|
|
696
|
+
* return await Option.asyncGen(async function* () {
|
|
697
|
+
* const normalized = yield* Option.Some(normalizeEmail(email));
|
|
698
|
+
* const existing = yield* await findExistingLead(normalized);
|
|
699
|
+
* const enriched = yield* await enrichLeadData(existing);
|
|
700
|
+
* const validated = yield* validateLead(enriched);
|
|
701
|
+
* return validated;
|
|
702
|
+
* });
|
|
703
|
+
* }
|
|
704
|
+
* ```
|
|
705
|
+
*
|
|
706
|
+
* @see {@link asyncGenAdapter} for better type inference and cleaner syntax
|
|
707
|
+
* @see {@link gen} for synchronous operations
|
|
708
|
+
*/
|
|
709
|
+
static async asyncGen(genFn) {
|
|
710
|
+
const iterator = genFn();
|
|
711
|
+
let nextArg;
|
|
712
|
+
let currentResult;
|
|
713
|
+
while (true) {
|
|
714
|
+
const next = await iterator.next(nextArg);
|
|
715
|
+
if (next.done) {
|
|
716
|
+
currentResult = Option.Some(next.value);
|
|
717
|
+
break;
|
|
718
|
+
}
|
|
719
|
+
let option = next.value;
|
|
720
|
+
if (isCapturedTrace(option)) option = option.value;
|
|
721
|
+
if (option.isNone()) {
|
|
722
|
+
currentResult = Option.None;
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
725
|
+
nextArg = await option.unwrap();
|
|
726
|
+
}
|
|
727
|
+
return currentResult;
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Async generator-based syntax for chaining Option operations with an adapter function.
|
|
731
|
+
*
|
|
732
|
+
* The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,
|
|
733
|
+
* automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
|
|
734
|
+
*
|
|
735
|
+
* Short-circuits on first `None`, returning singleton `None`. Uses async iteration
|
|
736
|
+
* instead of recursion to avoid stack overflow on deep chains.
|
|
737
|
+
*
|
|
738
|
+
* @template Eff - The effect type (inferred from usage)
|
|
739
|
+
* @template T - The return type of the generator
|
|
740
|
+
* @param genFn - An async generator function receiving an adapter `$`
|
|
741
|
+
* @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
|
|
742
|
+
*
|
|
743
|
+
* @example
|
|
744
|
+
* ```ts
|
|
745
|
+
* // No need to manually await - adapter handles it
|
|
746
|
+
* const result = await Option.asyncGenAdapter(async function* ($) {
|
|
747
|
+
* const a = yield* $(Option.Some(1)); // sync Option
|
|
748
|
+
* const b = yield* $(asyncOperation(a)); // Promise<Option> - auto-awaited
|
|
749
|
+
* const c = yield* $(Option.Some(3));
|
|
750
|
+
* return a + b + c;
|
|
751
|
+
* });
|
|
752
|
+
*
|
|
753
|
+
* // Complex workflow with database and API calls
|
|
754
|
+
* const userData = await Option.asyncGenAdapter(async function* ($) {
|
|
755
|
+
* const session = yield* $(getSession()); // Promise<Option<Session>>
|
|
756
|
+
* const userId = yield* $(Option.fromNullable(session?.userId));
|
|
757
|
+
* const profile = yield* $(await fetchProfile(userId)); // Promise<Option<Profile>>
|
|
758
|
+
* const preferences = yield* $(Option.fromNullable(profile?.preferences));
|
|
759
|
+
* const enriched = yield* $(await enrichPreferences(preferences));
|
|
760
|
+
* return enriched;
|
|
761
|
+
* });
|
|
762
|
+
*
|
|
763
|
+
* // Real-world: Optional data enrichment
|
|
764
|
+
* async function getProductDetails(productId: string): Promise<Option<ProductDetails>> {
|
|
765
|
+
* return await Option.asyncGenAdapter(async function* ($) {
|
|
766
|
+
* const product = yield* $(await fetchProduct(productId));
|
|
767
|
+
* const pricing = yield* $(await fetchPricing(product.sku));
|
|
768
|
+
* const inventory = yield* $(await checkInventory(product.id));
|
|
769
|
+
* const reviews = yield* $(await fetchReviews(product.id));
|
|
770
|
+
* const related = yield* $(await fetchRelatedProducts(product.category));
|
|
771
|
+
*
|
|
772
|
+
* return { product, pricing, inventory, reviews, related };
|
|
773
|
+
* });
|
|
774
|
+
* }
|
|
775
|
+
* ```
|
|
776
|
+
*
|
|
777
|
+
* @see {@link asyncGen} when you want explicit `await` for async operations
|
|
778
|
+
* @see {@link genAdapter} for synchronous operations
|
|
779
|
+
*/
|
|
780
|
+
static async asyncGenAdapter(genFn) {
|
|
781
|
+
const adapter = (option) => new AsyncOptionYieldWrap(option);
|
|
782
|
+
const iterator = genFn(adapter);
|
|
783
|
+
let nextArg;
|
|
784
|
+
let currentResult;
|
|
785
|
+
while (true) {
|
|
786
|
+
const next = await iterator.next(nextArg);
|
|
787
|
+
if (next.done) {
|
|
788
|
+
currentResult = Option.Some(next.value);
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
let option = await next.value.option;
|
|
792
|
+
if (isCapturedTrace(option)) option = option.value;
|
|
793
|
+
if (option.isNone()) {
|
|
794
|
+
currentResult = Option.None;
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
nextArg = await option.unwrap();
|
|
798
|
+
}
|
|
799
|
+
return currentResult;
|
|
800
|
+
}
|
|
275
801
|
};
|
|
276
802
|
|
|
277
803
|
//#endregion
|