@carbonteq/fp 0.9.1 → 0.11.1
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 +326 -97
- package/dist/errors.cjs +2 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -5
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts +2 -5
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs +1 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +332 -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 +330 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +340 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +77 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +77 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +338 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +29 -14
- package/dist/index.d.cts +10 -5
- package/dist/index.d.mts +10 -5
- package/dist/index.mjs +10 -5
- package/dist/match.cjs +376 -3
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +467 -8
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +467 -8
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +371 -3
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1547 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1380 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1380 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1545 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +650 -71
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +528 -39
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +528 -39
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +648 -70
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1346 -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 +1345 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +746 -81
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +799 -104
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +799 -104
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +742 -73
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +5 -4
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +9 -7
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +9 -7
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +4 -3
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +3 -3
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +4 -5
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +4 -5
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +2 -2
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +50 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +14 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +14 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +46 -3
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +60 -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 +240 -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 +244 -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 +154 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +157 -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 +54 -31
package/README.md
CHANGED
|
@@ -35,13 +35,13 @@ function getUserByEmail(user: { email?: string }): string | null {
|
|
|
35
35
|
return user.email ? user.email : null;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
function
|
|
39
|
-
return
|
|
38
|
+
function getUserAddress(email: string): string | null {
|
|
39
|
+
return email ? "Some Address" : null;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
const email = getUserByEmail({ email: "test@test.com" });
|
|
43
43
|
if (email) {
|
|
44
|
-
const address =
|
|
44
|
+
const address = getUserAddress(email);
|
|
45
45
|
if (address) {
|
|
46
46
|
console.log(`User ${email} has address: ${address}`);
|
|
47
47
|
} else {
|
|
@@ -50,12 +50,12 @@ if (email) {
|
|
|
50
50
|
} else {
|
|
51
51
|
console.error("Email not found");
|
|
52
52
|
}
|
|
53
|
-
//
|
|
53
|
+
// Example output: User test@test.com has address: Some Address
|
|
54
54
|
```
|
|
55
55
|
|
|
56
56
|
Now imagine if we had more complex use cases that involved more than two optional values. We would have to nest if statements and handle errors manually. This is where `fp` comes in.
|
|
57
57
|
|
|
58
|
-
###
|
|
58
|
+
### Using the `fp` library
|
|
59
59
|
|
|
60
60
|
```typescript
|
|
61
61
|
import { Option, matchOpt } from "@carbonteq/fp";
|
|
@@ -64,12 +64,12 @@ function getUserByEmail(user: { email?: string }): Option<string> {
|
|
|
64
64
|
return user.email ? Option.Some(user.email) : Option.None;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
function getUserAddress(
|
|
68
|
-
return
|
|
67
|
+
function getUserAddress(email: string): Option<string> {
|
|
68
|
+
return Option.Some("Some Address");
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
const res = getUserByEmail({ email: "test@test.com" }).flatZip((email) =>
|
|
72
|
-
getUserAddress(
|
|
72
|
+
getUserAddress(email),
|
|
73
73
|
);
|
|
74
74
|
|
|
75
75
|
matchOpt(res, {
|
|
@@ -80,14 +80,19 @@ matchOpt(res, {
|
|
|
80
80
|
console.error("User or Address not found");
|
|
81
81
|
},
|
|
82
82
|
});
|
|
83
|
-
//
|
|
83
|
+
// Example output: User test@test.com has address: Some Address
|
|
84
84
|
```
|
|
85
85
|
|
|
86
86
|
## Table of Contents
|
|
87
87
|
|
|
88
|
+
- [Examples](#examples)
|
|
88
89
|
- [Usage](#usage)
|
|
89
90
|
- [The `Result` type](#the-result-type)
|
|
90
91
|
- [The `Option` type](#the-option-type)
|
|
92
|
+
- [Fluent `match()` builder](#fluent-match-builder)
|
|
93
|
+
- [The `ExperimentalResult` type (Experimental)](#the-experimentalresult-type-experimental)
|
|
94
|
+
- [The `ExperimentalOption` type (Experimental)](#the-experimentaloption-type-experimental)
|
|
95
|
+
- [The `Flow` namespaces](#the-flow-namespaces)
|
|
91
96
|
- [Cheatsheet](#cheatsheet)
|
|
92
97
|
- [map](#map)
|
|
93
98
|
- [flatMap](#flatmap)
|
|
@@ -105,6 +110,15 @@ matchOpt(res, {
|
|
|
105
110
|
- [Synchronous Pipeline](#synchronous-pipeline)
|
|
106
111
|
- [Asynchronous Pipeline](#asynchronous-pipeline)
|
|
107
112
|
|
|
113
|
+
## Examples
|
|
114
|
+
|
|
115
|
+
Examples are split between stable and experimental APIs.
|
|
116
|
+
|
|
117
|
+
- Stable runnable examples live under `examples/result/`, `examples/option/`, and `examples/flow/`.
|
|
118
|
+
- Experimental runnable examples live under `examples/result-experimental/`, `examples/option-experimental/`, and `examples/flow-experimental/`.
|
|
119
|
+
|
|
120
|
+
See `examples/README.md` for the runnable index and file paths.
|
|
121
|
+
|
|
108
122
|
## Usage
|
|
109
123
|
|
|
110
124
|
## The `Result` type
|
|
@@ -118,6 +132,21 @@ const res1: Result<number, string> = Result.Ok(5); // Contains the value 5
|
|
|
118
132
|
const res2: Result<number, string> = Result.Err("Some Error"); // Contains the error "Some Error"
|
|
119
133
|
```
|
|
120
134
|
|
|
135
|
+
Async variants
|
|
136
|
+
|
|
137
|
+
In the stable API, async mappers/binders are allowed on the same methods. The async work stays inside the Result, so the return type is `Result<Promise<T>, E>`. Use `toPromise()` when you need `Promise<Result<T, E>>`.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
// Sync
|
|
141
|
+
Result.Ok(5).map((x) => x * 2); // Result<number, never>
|
|
142
|
+
Result.Ok(5).flatMap((x) => Result.Ok(x * 2));
|
|
143
|
+
|
|
144
|
+
// Async (stable)
|
|
145
|
+
const mapped = Result.Ok(5).map(async (x) => x * 2); // Result<Promise<number>, never>
|
|
146
|
+
const chained = Result.Ok(5).flatMap(async (x) => Result.Ok(x * 2)); // Result<Promise<number>, never>
|
|
147
|
+
const resolved = await chained.toPromise(); // Promise<Result<number, never>>
|
|
148
|
+
```
|
|
149
|
+
|
|
121
150
|
## The `Option` type
|
|
122
151
|
|
|
123
152
|
The `Option` type represents a value that might or might not be present. It eliminates the need for manual checks for `null` or `undefined`.
|
|
@@ -129,6 +158,128 @@ const opt1: Option<number> = Option.Some(5); // Contains the value 5
|
|
|
129
158
|
const opt2: Option<number> = Option.None; // Contains no value (None)
|
|
130
159
|
```
|
|
131
160
|
|
|
161
|
+
Async variants
|
|
162
|
+
|
|
163
|
+
In the stable API, async mappers/predicates are allowed on the same methods. The async work stays inside the Option, so the return type is `Option<Promise<T>>`. Use `toPromise()` when you need `Promise<Option<T>>`.
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
// Sync
|
|
167
|
+
Option.Some(5).map((x) => x * 2); // Option<number>
|
|
168
|
+
Option.Some(5).flatMap((x) => Option.Some(x * 2));
|
|
169
|
+
|
|
170
|
+
// Async (stable)
|
|
171
|
+
const mapped = Option.Some(5).map(async (x) => x * 2); // Option<Promise<number>>
|
|
172
|
+
const chained = Option.Some(5).flatMap(async (x) => Option.Some(x * 2)); // Option<Promise<number>>
|
|
173
|
+
const filtered = Option.Some(5).filter(async (x) => x > 3); // Option<Promise<number>>
|
|
174
|
+
const resolved = await filtered.toPromise(); // Promise<Option<number>>
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Fluent `match()` builder
|
|
178
|
+
|
|
179
|
+
Use `match()` for fluent, exhaustive pattern matching across stable and experimental `Option`/`Result` values, plus generic discriminated unions.
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { match, P, Result } from "@carbonteq/fp";
|
|
183
|
+
|
|
184
|
+
const message = match(Result.Ok(42) as Result<number, string>)
|
|
185
|
+
.with(P.Ok(P.eq(42)), (value) => `exactly ${value}`)
|
|
186
|
+
.with(P.Ok(P.not(P.oneOf(42, 43))), () => "ok but not 42 or 43")
|
|
187
|
+
.with(P.Ok(), (value) => `other ok: ${value}`)
|
|
188
|
+
.with(P.Err(), (error) => `error: ${error}`)
|
|
189
|
+
.exhaustive();
|
|
190
|
+
|
|
191
|
+
const branch = match(Result.Err("timeout") as Result<number, string>)
|
|
192
|
+
.when(P.IsOk, () => "ok")
|
|
193
|
+
.when(P.IsErr, () => "err")
|
|
194
|
+
.otherwise(() => "other");
|
|
195
|
+
|
|
196
|
+
const combined = match(Result.Ok(42) as Result<number, string>)
|
|
197
|
+
.with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
|
|
198
|
+
.with(P.Ok(), () => "miss")
|
|
199
|
+
.with(P.Err(), () => "err")
|
|
200
|
+
.exhaustive();
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Handler inputs:
|
|
204
|
+
|
|
205
|
+
- `.with(P.Ok(...), handler)` receives the unwrapped `Ok` value.
|
|
206
|
+
- `.with(P.Err(...), handler)` receives the unwrapped `Err` value.
|
|
207
|
+
- `.with(P.Some(...), handler)` receives the unwrapped `Some` value.
|
|
208
|
+
- `.with(P._, handler)` and `.when(...)` handlers receive the whole matched value.
|
|
209
|
+
|
|
210
|
+
`match()` is intentionally synchronous. If you have async-inner stable values, settle first:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
import { match, Result } from "@carbonteq/fp";
|
|
214
|
+
|
|
215
|
+
const asyncResult = Result.Ok(Promise.resolve(10)); // Result<Promise<number>, never>
|
|
216
|
+
const settled = await asyncResult.toPromise(); // Promise<Result<number, never>>
|
|
217
|
+
|
|
218
|
+
const label = match(settled)
|
|
219
|
+
.with("Ok", (value) => `value=${value}`)
|
|
220
|
+
.with("Err", () => "error")
|
|
221
|
+
.exhaustive();
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
## The `ExperimentalResult` type (Experimental)
|
|
227
|
+
|
|
228
|
+
`ExperimentalResult` differs from the stable `Result` by providing explicit async methods like `mapAsync` and `flatMapAsync` that return `Promise<ExperimentalResult<T, unknown>>` directly, rather than returning `Result<Promise<T>, E>` and requiring `toPromise()`. Returned-promise rejections become `Err` with the original rejection value, which need not be an `Error`. Narrow errors before accessing properties, for example `error instanceof Error ? error.message : String(error)`. A promise-typed mapper that throws synchronously still rejects the method's promise. Both methods skip the mapper for an existing `Err`. It also includes generator-based APIs (`gen`, `asyncGen`, and adapter variants) used by `Flow`.
|
|
229
|
+
|
|
230
|
+
`ExperimentalResult.validate` now accepts synchronous validators only. Migrate `await result.validate([asyncValidator])` to `await result.validateAsync([asyncValidator])`. `validateAsync` always returns a Promise, including when the input is already Err. Stable `Result.validate` is unchanged.
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
import { ExperimentalResult } from "@carbonteq/fp";
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## The `ExperimentalOption` type (Experimental)
|
|
237
|
+
|
|
238
|
+
`ExperimentalOption` mirrors the stable `Option` API but provides explicit async methods like `mapAsync`, `flatMapAsync`, and `filterAsync` that return `Promise<ExperimentalOption<T>>` rather than `Option<Promise<T>>`. It also includes generator-based APIs (`gen`, `asyncGen`, and adapter variants) and is the `Option` type used by `Flow`.
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
import { ExperimentalOption } from "@carbonteq/fp";
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
## The `Flow` namespaces
|
|
247
|
+
|
|
248
|
+
`Flow` is the stable generator namespace and works with stable `Option` + `Result`, returning stable `Result`.
|
|
249
|
+
|
|
250
|
+
Generator composition in all six namespaces (`Option`, `Result`, `Flow`, and their experimental counterparts) runs suspended `finally` cleanup when a yielded effect fails. Cleanup may yield further effects and use their resumed values; async generators wait for cleanup to settle before returning. Once a runner has observed a primary failure or exception, subsequent cleanup failures do not replace it. JavaScript's ordinary `finally` control-flow rules still apply before the runner observes a failure.
|
|
251
|
+
|
|
252
|
+
```typescript
|
|
253
|
+
import { Flow, Option, Result, UnwrappedNone } from "@carbonteq/fp";
|
|
254
|
+
|
|
255
|
+
const result = Flow.gen(function* () {
|
|
256
|
+
const a = yield* Option.Some(5);
|
|
257
|
+
const b = yield* Result.Ok(10);
|
|
258
|
+
const c = yield* Option.fromNullable(20);
|
|
259
|
+
return a + b + c;
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// Result<number, UnwrappedNone>
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`ExperimentalFlow` is the experimental counterpart and works with `ExperimentalOption` + `ExperimentalResult`, returning `ExperimentalResult`.
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
import {
|
|
269
|
+
ExperimentalFlow,
|
|
270
|
+
ExperimentalOption,
|
|
271
|
+
ExperimentalResult,
|
|
272
|
+
} from "@carbonteq/fp";
|
|
273
|
+
|
|
274
|
+
const result = ExperimentalFlow.gen(function* () {
|
|
275
|
+
const a = yield* ExperimentalOption.Some(5);
|
|
276
|
+
const b = yield* ExperimentalResult.Ok(10);
|
|
277
|
+
return a + b;
|
|
278
|
+
});
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Both namespaces provide `gen`, `genAdapter`, `asyncGen`, and `asyncGenAdapter`.
|
|
282
|
+
|
|
132
283
|
---
|
|
133
284
|
|
|
134
285
|
## Cheatsheet
|
|
@@ -137,6 +288,8 @@ const opt2: Option<number> = Option.None; // Contains no value (None)
|
|
|
137
288
|
|
|
138
289
|
Transforms the `Some` or `Ok` value inside `Option` or `Result`.
|
|
139
290
|
|
|
291
|
+
If your mapper is async, `map` returns `Option<Promise<U>>` or `Result<Promise<U>, E>`. Use `toPromise()` when you need a resolved `Option`/`Result`.
|
|
292
|
+
|
|
140
293
|
Let's say we want to apply a 10% bonus to the account balance of a user.
|
|
141
294
|
|
|
142
295
|
```typescript
|
|
@@ -159,7 +312,7 @@ async function applyBonus() {
|
|
|
159
312
|
return balanceOption;
|
|
160
313
|
}
|
|
161
314
|
|
|
162
|
-
console.log(await applyBonus()); //
|
|
315
|
+
console.log(await applyBonus()); // Example output: Some(110)
|
|
163
316
|
```
|
|
164
317
|
|
|
165
318
|
#### `flatMap`
|
|
@@ -206,7 +359,7 @@ const processUser = async (
|
|
|
206
359
|
return validationResult;
|
|
207
360
|
};
|
|
208
361
|
|
|
209
|
-
console.log(await processUser("Alice", 30)); //
|
|
362
|
+
console.log(await processUser("Alice", 30)); // Example output: Result.Ok("User Alice saved successfully!")
|
|
210
363
|
|
|
211
364
|
/* validationResult is of type Result<string, Error> instead of Result<Result<string, Error>, Error> (which is what would have happened if we used map instead of flatMap) */
|
|
212
365
|
```
|
|
@@ -237,14 +390,14 @@ async function applyDiscount(
|
|
|
237
390
|
return originalPrice; //originalPrice is of type Result<[number, number], Error>
|
|
238
391
|
}
|
|
239
392
|
|
|
240
|
-
console.log(await applyDiscount("123")); //
|
|
393
|
+
console.log(await applyDiscount("123")); // Example output: Result.Ok([100, 90])
|
|
241
394
|
```
|
|
242
395
|
|
|
243
396
|
Here `derivedPair` is a `Result<[number, number], Error>`. Note that `T` = `100` and `U` = `90`.
|
|
244
397
|
|
|
245
398
|
#### `flatZip`
|
|
246
399
|
|
|
247
|
-
Combines the current `Result<T, E>` with
|
|
400
|
+
Combines the current `Result<T, E>` with a **dependent** `Result<U, E2>` produced from `T`, or the current `Option<T>` with a dependent `Option<U>` produced from `T`. Unlike `zip`, which pairs a value with a plain derived value, `flatZip` expects the callback to return a `Result`/`Option` and then flattens the outcome into `[T, U]`. It proceeds only when both steps are `Ok`/`Some`; otherwise, it propagates the first `Err`/`None`.
|
|
248
401
|
|
|
249
402
|
Lets say we want to combine the product price and product stock into a tuple `[number, number]`.
|
|
250
403
|
|
|
@@ -258,10 +411,10 @@ async function fetchProductPrice(productId: string): Promise<Option<number>> {
|
|
|
258
411
|
return Option.Some(100);
|
|
259
412
|
}
|
|
260
413
|
|
|
261
|
-
// Simulated function to fetch product stock
|
|
262
|
-
async function fetchProductStock(
|
|
263
|
-
// Simulate fetching stock from a database
|
|
264
|
-
await Promise.resolve(
|
|
414
|
+
// Simulated function to fetch product stock (receives price, returns Option)
|
|
415
|
+
async function fetchProductStock(price: number): Promise<Option<number>> {
|
|
416
|
+
// Simulate fetching stock from a database based on price
|
|
417
|
+
await Promise.resolve(price);
|
|
265
418
|
return Option.Some(50);
|
|
266
419
|
}
|
|
267
420
|
|
|
@@ -276,18 +429,18 @@ async function fetchProductDetails(
|
|
|
276
429
|
return productDetails; // Option<[number, number]>
|
|
277
430
|
}
|
|
278
431
|
|
|
279
|
-
console.log(await fetchProductDetails("123")); //
|
|
432
|
+
console.log(await fetchProductDetails("123")); // Example output: Option.Some([100, 50])
|
|
280
433
|
```
|
|
281
434
|
|
|
282
435
|
## Comparison of `map`, `flatMap`, `zip`, and `flatZip`
|
|
283
436
|
|
|
284
437
|
| **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** |
|
|
285
438
|
| --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
|
|
286
|
-
| **Purpose** | Transforms the value inside an `Ok` or `Some`. | Chains dependent computations where each computation returns a `Result` or `Option`. | Combines the current value with another derived value into a tuple `[T, U]`. |
|
|
439
|
+
| **Purpose** | Transforms the value inside an `Ok` or `Some`. | Chains dependent computations where each computation returns a `Result` or `Option`. | Combines the current value with another derived value into a tuple `[T, U]`. | Chains a dependent computation returning `Result`/`Option` and combines both values into `[T, U]`. |
|
|
287
440
|
| **Input** | A function `(val: T) => U`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` to transform the current value into another `Result` or `Option`. | A function `(val: T) => U` to derive a new value `U` from the current value `T`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` that returns another `Result` or `Option`. |
|
|
288
441
|
| **Output** | `Result<U, E>`, `Option<U>` | `Result<U, E>`, `Option<U>` | `Result<[T, U], E>`, `Option<[T, U]>` | `Result<[T, U], E>`, `Option<[T, U]>`. |
|
|
289
442
|
| **Error Propagation** | Propagates `Err`/`None` if the `Result`/`Option` is `Err`/`None`. | Propagates the first `Err`/`None` encountered in the chain. | Propagates `Err`/`None` if the current `Result`/`Option` or derived value is `Err`/`None`. | Propagates the first `Err`/`None` encountered between the two `Result`/`Option` values. |
|
|
290
|
-
| **Use Case** | When you want to transform a value inside `Ok`/`Some`. | When the next computation depends on the current value and returns a `Result`/`Option`. | When you want to pair the current value with a derived one. | When you want to
|
|
443
|
+
| **Use Case** | When you want to transform a value inside `Ok`/`Some`. | When the next computation depends on the current value and returns a `Result`/`Option`. | When you want to pair the current value with a derived one. | When you want to pair the current value with a dependent `Result`/`Option` computation. |
|
|
291
444
|
|
|
292
445
|
---
|
|
293
446
|
|
|
@@ -338,18 +491,15 @@ async function findUserById(id: number): Promise<Option<number>> {
|
|
|
338
491
|
return Option.Some(id);
|
|
339
492
|
}
|
|
340
493
|
|
|
341
|
-
// A safe function that returns a string
|
|
342
|
-
async function safeFindUserById(id: number): Promise<
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
(res) => `User: ${res}`,
|
|
346
|
-
);
|
|
347
|
-
return res;
|
|
494
|
+
// A safe function that returns a string message (not an Option) - mapOr returns the value directly
|
|
495
|
+
async function safeFindUserById(id: number): Promise<string> {
|
|
496
|
+
const userOpt = await findUserById(id);
|
|
497
|
+
return userOpt.mapOr(`User not found`, (res) => `User: ${res}`);
|
|
348
498
|
}
|
|
349
499
|
|
|
350
500
|
// Example usage
|
|
351
|
-
console.log(await safeFindUserById(10)); //
|
|
352
|
-
console.log(await safeFindUserById(0)); //
|
|
501
|
+
console.log(await safeFindUserById(10)); // User: 10
|
|
502
|
+
console.log(await safeFindUserById(0)); // User not found
|
|
353
503
|
```
|
|
354
504
|
|
|
355
505
|
#### `all`
|
|
@@ -383,6 +533,7 @@ type Like = {
|
|
|
383
533
|
type Reply = {
|
|
384
534
|
replyId: string;
|
|
385
535
|
postId: Post["postId"];
|
|
536
|
+
data: string;
|
|
386
537
|
createdAt: Date | string;
|
|
387
538
|
author: User["userId"];
|
|
388
539
|
};
|
|
@@ -447,11 +598,11 @@ async function getUserData(userId: string) {
|
|
|
447
598
|
const hash = userIdRes.flatMap(generateHash);
|
|
448
599
|
|
|
449
600
|
const userData = await Result.all(
|
|
450
|
-
user,
|
|
451
|
-
posts,
|
|
452
|
-
likes,
|
|
453
|
-
replies,
|
|
454
|
-
hash,
|
|
601
|
+
user,
|
|
602
|
+
posts,
|
|
603
|
+
likes,
|
|
604
|
+
replies,
|
|
605
|
+
hash,
|
|
455
606
|
).toPromise();
|
|
456
607
|
|
|
457
608
|
matchRes(userData, {
|
|
@@ -547,9 +698,10 @@ const validatedOk = Result.Ok("password321!").validate([
|
|
|
547
698
|
]);
|
|
548
699
|
console.log(validatedOk.unwrap()); // password321!
|
|
549
700
|
|
|
550
|
-
const validatedErr =
|
|
551
|
-
|
|
552
|
-
|
|
701
|
+
const validatedErr = Result.Ok("pword").validate([
|
|
702
|
+
hasMinimumLength,
|
|
703
|
+
hasSpecialCharacters,
|
|
704
|
+
]);
|
|
553
705
|
console.log(validatedErr.unwrapErr()); // [Error: Password must be at least 8 characters, Error: Password must contain at least one special character]
|
|
554
706
|
|
|
555
707
|
const validatedErrs = await Result.Ok("password123!")
|
|
@@ -558,9 +710,13 @@ const validatedErrs = await Result.Ok("password123!")
|
|
|
558
710
|
console.log(validatedErrs.unwrapErr()); // [Error: New password cannot be the same as previous password]
|
|
559
711
|
```
|
|
560
712
|
|
|
561
|
-
#### `unwrap`, `
|
|
713
|
+
#### `unwrap`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
|
|
714
|
+
|
|
715
|
+
These functions extract values from a `Result`. `Option` also supports `unwrap`, `unwrapOr`, `unwrapOrElse`, and `safeUnwrap`.
|
|
716
|
+
|
|
717
|
+
For stable `Option`, `unwrapOr` supplies a default and `unwrapOrElse` computes it only for absence. Promise-backed options wait for settlement and always return a promise, including after settling to None. Rejected payloads still reject without invoking the factory.
|
|
562
718
|
|
|
563
|
-
|
|
719
|
+
For `Option<Promise<T>>`, a resolved fallback or factory has return type `Awaited<T> | Promise<Awaited<T>>`: `Option.None` can be widened to that receiver type but still returns a resolved fallback synchronously. A promised fallback or promise-returning factory guarantees `Promise<Awaited<T>>`. Fallbacks may also be a union of resolved and promised values. Ordinary synchronous options stay synchronous, and direct `Option.None` calls infer the fallback's type.
|
|
564
720
|
|
|
565
721
|
```typescript
|
|
566
722
|
import { Result } from "@carbonteq/fp";
|
|
@@ -660,11 +816,7 @@ Creates a `Result` based on a predicate function - returns `Ok` with the value i
|
|
|
660
816
|
import { Result } from "@carbonteq/fp";
|
|
661
817
|
|
|
662
818
|
const score = 85;
|
|
663
|
-
const passed = Result.fromPredicate(
|
|
664
|
-
score,
|
|
665
|
-
(s) => s >= 60,
|
|
666
|
-
"Score too low",
|
|
667
|
-
);
|
|
819
|
+
const passed = Result.fromPredicate(score, (s) => s >= 60, "Score too low");
|
|
668
820
|
console.log(passed); // Ok(85)
|
|
669
821
|
|
|
670
822
|
const failed = Result.fromPredicate(45, (s) => s >= 60, "Score too low");
|
|
@@ -685,7 +837,7 @@ import { Result } from "@carbonteq/fp";
|
|
|
685
837
|
function parseJson(json: string): Result<unknown, Error> {
|
|
686
838
|
return Result.tryCatch(
|
|
687
839
|
() => JSON.parse(json),
|
|
688
|
-
(e) => e instanceof Error ? e : new Error(String(e)),
|
|
840
|
+
(e) => (e instanceof Error ? e : new Error(String(e))),
|
|
689
841
|
);
|
|
690
842
|
}
|
|
691
843
|
|
|
@@ -700,17 +852,19 @@ Wraps an asynchronous operation in a `Result`, catching any exceptions and conve
|
|
|
700
852
|
```typescript
|
|
701
853
|
import { Result } from "@carbonteq/fp";
|
|
702
854
|
|
|
703
|
-
async function fetchUserData(
|
|
855
|
+
async function fetchUserData(
|
|
856
|
+
id: string,
|
|
857
|
+
): Promise<Result<{ name: string }, Error>> {
|
|
704
858
|
return Result.tryAsyncCatch(
|
|
705
859
|
async () => {
|
|
706
860
|
const response = await fetch(`/api/users/${id}`);
|
|
707
861
|
return response.json();
|
|
708
862
|
},
|
|
709
|
-
(e) => e instanceof Error ? e : new Error(String(e)),
|
|
863
|
+
(e) => (e instanceof Error ? e : new Error(String(e))),
|
|
710
864
|
);
|
|
711
865
|
}
|
|
712
866
|
|
|
713
|
-
const user = await fetchUserData("123")
|
|
867
|
+
const user = await fetchUserData("123");
|
|
714
868
|
console.log(user); // Ok({ name: "..." }) or Err(Error: ...)
|
|
715
869
|
```
|
|
716
870
|
|
|
@@ -814,36 +968,6 @@ const optFromErr = failure.toOption();
|
|
|
814
968
|
console.log(optFromErr); // None
|
|
815
969
|
```
|
|
816
970
|
|
|
817
|
-
#### `Option.fromPromise`
|
|
818
|
-
|
|
819
|
-
Wraps a `Promise<Option<T>>` as an `Option<Promise<T>>`, enabling async chaining.
|
|
820
|
-
|
|
821
|
-
```typescript
|
|
822
|
-
import { Option } from "@carbonteq/fp";
|
|
823
|
-
|
|
824
|
-
async function fetchUser(id: string): Promise<Option<{ name: string }>> {
|
|
825
|
-
return id === "1" ? Option.Some({ name: "Alice" }) : Option.None;
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
const userOpt = Option.fromPromise(fetchUser("1"));
|
|
829
|
-
console.log(userOpt); // Some(Promise<{ name: "Alice" }>)
|
|
830
|
-
```
|
|
831
|
-
|
|
832
|
-
#### `Result.fromPromise`
|
|
833
|
-
|
|
834
|
-
Wraps a `Promise<Result<T, E>>` as a `Result<Promise<T>, E>`, enabling async chaining.
|
|
835
|
-
|
|
836
|
-
```typescript
|
|
837
|
-
import { Result } from "@carbonteq/fp";
|
|
838
|
-
|
|
839
|
-
async function fetchData(id: string): Promise<Result<string, Error>> {
|
|
840
|
-
return id === "1" ? Result.Ok("Data") : Result.Err(new Error("Not found"));
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
const dataRes = Result.fromPromise(fetchData("1"));
|
|
844
|
-
console.log(dataRes); // Ok(Promise<"Data">)
|
|
845
|
-
```
|
|
846
|
-
|
|
847
971
|
#### `Result.zipErr`
|
|
848
972
|
|
|
849
973
|
Runs a validation/binding function on the Ok value that can produce a new error, while preserving the original Ok value. If the function returns an `Err`, that error is returned. If the initial result is already `Err`, it short-circuits and returns that error.
|
|
@@ -853,7 +977,9 @@ import { Result } from "@carbonteq/fp";
|
|
|
853
977
|
|
|
854
978
|
const checkPermissions = (userId: string) =>
|
|
855
979
|
Result.Ok(userId).zipErr((id) =>
|
|
856
|
-
id === "guest"
|
|
980
|
+
id === "guest"
|
|
981
|
+
? Result.Err("Guest users have limited access")
|
|
982
|
+
: Result.Ok(undefined),
|
|
857
983
|
);
|
|
858
984
|
|
|
859
985
|
const admin = checkPermissions("admin-123");
|
|
@@ -865,8 +991,9 @@ console.log(guest); // Err("Guest users have limited access")
|
|
|
865
991
|
const okNoChange = Result.Ok("42").zipErr((id) => Result.Ok(id.length));
|
|
866
992
|
console.log(okNoChange); // Ok("42")
|
|
867
993
|
|
|
868
|
-
const alreadyFailed = Result.Err<string, string>("Network error")
|
|
869
|
-
|
|
994
|
+
const alreadyFailed = Result.Err<string, string>("Network error").zipErr(() =>
|
|
995
|
+
Result.Err("Validation error"),
|
|
996
|
+
);
|
|
870
997
|
console.log(alreadyFailed); // Err("Network error") - short-circuits
|
|
871
998
|
```
|
|
872
999
|
|
|
@@ -877,17 +1004,18 @@ console.log(alreadyFailed); // Err("Network error") - short-circuits
|
|
|
877
1004
|
```typescript
|
|
878
1005
|
import { Result } from "@carbonteq/fp";
|
|
879
1006
|
|
|
880
|
-
const res = Result.Err<
|
|
881
|
-
|
|
1007
|
+
const res = Result.Err<Error, number>(new Error("boom")).mapErr(
|
|
1008
|
+
(e) => e.message,
|
|
1009
|
+
);
|
|
882
1010
|
console.log(res); // Err("boom")
|
|
883
1011
|
|
|
884
1012
|
const ok = Result.Ok("42").zipErr((value) =>
|
|
885
|
-
value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
|
|
1013
|
+
value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
|
|
886
1014
|
);
|
|
887
1015
|
console.log(ok); // Ok("42")
|
|
888
1016
|
|
|
889
1017
|
const err = Result.Ok("0").zipErr((value) =>
|
|
890
|
-
value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
|
|
1018
|
+
value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
|
|
891
1019
|
);
|
|
892
1020
|
console.log(err); // Err("invalid")
|
|
893
1021
|
```
|
|
@@ -920,7 +1048,9 @@ Executes a side effect function for `Some` or `Ok` values, then returns the orig
|
|
|
920
1048
|
import { Result } from "@carbonteq/fp";
|
|
921
1049
|
|
|
922
1050
|
// Simulated database functions
|
|
923
|
-
async function findUserById(
|
|
1051
|
+
async function findUserById(
|
|
1052
|
+
userId: number,
|
|
1053
|
+
): Promise<Result<Record<string, number>, string>> {
|
|
924
1054
|
// Simulate a database lookup
|
|
925
1055
|
await Promise.resolve(userId);
|
|
926
1056
|
if (userId === 0) {
|
|
@@ -929,7 +1059,10 @@ async function findUserById(userId: number): Promise<Result<Record<string, numbe
|
|
|
929
1059
|
return Result.Ok({ id: userId, balance: 100 });
|
|
930
1060
|
}
|
|
931
1061
|
|
|
932
|
-
function updateBalance(
|
|
1062
|
+
function updateBalance(
|
|
1063
|
+
user: Record<string, number>,
|
|
1064
|
+
amount: number,
|
|
1065
|
+
): Result<Record<string, number>, string> {
|
|
933
1066
|
if (user.balance < amount) {
|
|
934
1067
|
return Result.Err("Insufficient funds");
|
|
935
1068
|
}
|
|
@@ -940,7 +1073,9 @@ function updateBalance(user: Record<string, number>, amount: number): Result<Rec
|
|
|
940
1073
|
const res = (await findUserById(1))
|
|
941
1074
|
.tap((user) => console.log(`[Audit] User found: ${user.id}`))
|
|
942
1075
|
.flatMap((user) => updateBalance(user, 10))
|
|
943
|
-
.tap((updated) =>
|
|
1076
|
+
.tap((updated) =>
|
|
1077
|
+
console.log(`[Transaction] New balance: $${updated.balance}`),
|
|
1078
|
+
)
|
|
944
1079
|
.tapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
|
|
945
1080
|
|
|
946
1081
|
console.log(res); // Result.Ok({ id: 1, balance: 90 })
|
|
@@ -958,7 +1093,7 @@ const logged = result.tapErr((err) => {
|
|
|
958
1093
|
console.error(`[Error Log] ${new Date().toISOString()}: ${err}`);
|
|
959
1094
|
});
|
|
960
1095
|
console.log(logged); // Err("Connection failed")
|
|
961
|
-
//
|
|
1096
|
+
// Example output: [Error Log] 2025-01-07T...: Connection failed
|
|
962
1097
|
```
|
|
963
1098
|
|
|
964
1099
|
#### `Result.orElse`
|
|
@@ -969,11 +1104,15 @@ Recovers from an error by providing a fallback `Result`. If the current result i
|
|
|
969
1104
|
import { Result } from "@carbonteq/fp";
|
|
970
1105
|
|
|
971
1106
|
function fetchFromCache(id: string): Result<string, Error> {
|
|
972
|
-
return id === "cached"
|
|
1107
|
+
return id === "cached"
|
|
1108
|
+
? Result.Ok("Cached data")
|
|
1109
|
+
: Result.Err(new Error("Not in cache"));
|
|
973
1110
|
}
|
|
974
1111
|
|
|
975
1112
|
function fetchFromAPI(id: string): Result<string, Error> {
|
|
976
|
-
return id === "1"
|
|
1113
|
+
return id === "1"
|
|
1114
|
+
? Result.Ok("API data")
|
|
1115
|
+
: Result.Err(new Error("Not found"));
|
|
977
1116
|
}
|
|
978
1117
|
|
|
979
1118
|
const cached = fetchFromCache("cached").orElse((err) => fetchFromAPI("1"));
|
|
@@ -1008,6 +1147,51 @@ const allNone = Option.any(Option.None, Option.None, Option.None);
|
|
|
1008
1147
|
console.log(allNone); // None
|
|
1009
1148
|
```
|
|
1010
1149
|
|
|
1150
|
+
#### `ExperimentalOption.gen`, `genAdapter`, `asyncGen`, `asyncGenAdapter`
|
|
1151
|
+
|
|
1152
|
+
Experimental generator-based methods for chaining Option operations with imperative-style syntax.
|
|
1153
|
+
|
|
1154
|
+
```typescript
|
|
1155
|
+
import { ExperimentalOption as Option } from "@carbonteq/fp";
|
|
1156
|
+
|
|
1157
|
+
// Option.gen - simple sync chains (no adapter needed)
|
|
1158
|
+
const syncResult = Option.gen(function* () {
|
|
1159
|
+
const a = yield* Option.Some(1);
|
|
1160
|
+
const b = yield* Option.Some(2);
|
|
1161
|
+
return a + b;
|
|
1162
|
+
});
|
|
1163
|
+
console.log(syncResult); // Some(3)
|
|
1164
|
+
|
|
1165
|
+
// Option.asyncGen - async chains with explicit await
|
|
1166
|
+
const asyncResult = await Option.asyncGen(async function* () {
|
|
1167
|
+
const id = yield* Option.Some(1);
|
|
1168
|
+
const data = yield* await fetchUserData(id); // await Promise<Option> first
|
|
1169
|
+
const validated = yield* validate(data);
|
|
1170
|
+
return validated;
|
|
1171
|
+
});
|
|
1172
|
+
|
|
1173
|
+
// Option.genAdapter - better type inference for complex sync chains
|
|
1174
|
+
const complexSync = Option.genAdapter(function* ($) {
|
|
1175
|
+
const user = yield* $(fetchUser(123)); // sync Option
|
|
1176
|
+
const profile = yield* $(user.profile); // sync Option
|
|
1177
|
+
const valid = yield* $(validate(profile)); // sync Option
|
|
1178
|
+
return valid;
|
|
1179
|
+
});
|
|
1180
|
+
|
|
1181
|
+
// Option.asyncGenAdapter - cleaner async with auto-await handling
|
|
1182
|
+
const complexAsync = await Option.asyncGenAdapter(async function* ($) {
|
|
1183
|
+
const user = yield* $(fetchUser(123)); // sync or async Option
|
|
1184
|
+
const orders = yield* $(fetchOrders(user)); // Promise<Option> - auto-awaited
|
|
1185
|
+
const total = yield* $(calculateTotal(orders));
|
|
1186
|
+
return total;
|
|
1187
|
+
});
|
|
1188
|
+
```
|
|
1189
|
+
|
|
1190
|
+
**Key differences:**
|
|
1191
|
+
|
|
1192
|
+
- `gen` / `asyncGen`: Simple, direct `yield*` with Option values
|
|
1193
|
+
- `genAdapter` / `asyncGenAdapter`: Uses `$()` adapter for better type inference and cleaner syntax
|
|
1194
|
+
|
|
1011
1195
|
#### `Result.any`
|
|
1012
1196
|
|
|
1013
1197
|
Returns the first `Ok` from a list of `Result`s, or collects all errors if all are `Err`.
|
|
@@ -1030,6 +1214,53 @@ const allErrors = Result.any(
|
|
|
1030
1214
|
console.log(allErrors); // Err(["Error 1", "Error 2", "Error 3"])
|
|
1031
1215
|
```
|
|
1032
1216
|
|
|
1217
|
+
#### `ExperimentalResult.gen`, `genAdapter`, `asyncGen`, `asyncGenAdapter`
|
|
1218
|
+
|
|
1219
|
+
Experimental generator-based methods for chaining Result operations with imperative-style syntax.
|
|
1220
|
+
|
|
1221
|
+
```typescript
|
|
1222
|
+
import { ExperimentalResult as Result } from "@carbonteq/fp";
|
|
1223
|
+
|
|
1224
|
+
// Result.gen - simple sync chains (no adapter needed)
|
|
1225
|
+
const syncResult = Result.gen(function* () {
|
|
1226
|
+
const a = yield* Result.Ok(1);
|
|
1227
|
+
const b = yield* Result.Ok(2);
|
|
1228
|
+
return a + b;
|
|
1229
|
+
});
|
|
1230
|
+
console.log(syncResult); // Ok(3)
|
|
1231
|
+
|
|
1232
|
+
// Result.asyncGen - async chains with explicit await
|
|
1233
|
+
const asyncResult = await Result.asyncGen(async function* () {
|
|
1234
|
+
const id = yield* Result.Ok(1);
|
|
1235
|
+
const data = yield* await fetchUserData(id); // await Promise<Result> first
|
|
1236
|
+
const validated = yield* validate(data);
|
|
1237
|
+
return validated;
|
|
1238
|
+
});
|
|
1239
|
+
|
|
1240
|
+
// Result.genAdapter - better type inference for complex sync chains
|
|
1241
|
+
const complexSync = Result.genAdapter(function* ($) {
|
|
1242
|
+
const user = yield* $(fetchUser(123)); // sync Result
|
|
1243
|
+
const profile = yield* $(user.profile); // sync Result
|
|
1244
|
+
const valid = yield* $(validate(profile)); // sync Result
|
|
1245
|
+
return valid;
|
|
1246
|
+
});
|
|
1247
|
+
|
|
1248
|
+
// Result.asyncGenAdapter - cleaner async with auto-await handling
|
|
1249
|
+
const complexAsync = await Result.asyncGenAdapter(async function* ($) {
|
|
1250
|
+
const user = yield* $(fetchUser(123)); // sync or async Result
|
|
1251
|
+
const orders = yield* $(fetchOrders(user)); // Promise<Result> - auto-awaited
|
|
1252
|
+
const total = yield* $(calculateTotal(orders));
|
|
1253
|
+
return total;
|
|
1254
|
+
});
|
|
1255
|
+
```
|
|
1256
|
+
|
|
1257
|
+
**Key differences:**
|
|
1258
|
+
|
|
1259
|
+
- `gen` / `asyncGen`: Simple, direct `yield*` with Result values
|
|
1260
|
+
- `genAdapter` / `asyncGenAdapter`: Uses `$()` adapter for better type inference and cleaner syntax
|
|
1261
|
+
|
|
1262
|
+
---
|
|
1263
|
+
|
|
1033
1264
|
## Build Your First Pipeline
|
|
1034
1265
|
|
|
1035
1266
|
Let's build a pipeline for processing an e-commerce order. This example demonstrates handling user input validation, inventory checks, and order processing.
|
|
@@ -1108,7 +1339,7 @@ matchRes(result, {
|
|
|
1108
1339
|
},
|
|
1109
1340
|
});
|
|
1110
1341
|
|
|
1111
|
-
//
|
|
1342
|
+
// Example output:
|
|
1112
1343
|
// Order confirmed! Order ID: ORD-1716888600000
|
|
1113
1344
|
// Total: $59.98
|
|
1114
1345
|
// Order: {"productId":"PROD-123","quantity":2,"userId":"USER-456"}
|
|
@@ -1119,8 +1350,7 @@ matchRes(result, {
|
|
|
1119
1350
|
Let's build an asynchronous pipeline for a user registration system that includes credentials verification and profile setup.
|
|
1120
1351
|
|
|
1121
1352
|
```typescript
|
|
1122
|
-
import { matchRes } from "
|
|
1123
|
-
import { Result } from "@/result.js";
|
|
1353
|
+
import { matchRes, Result } from "@carbonteq/fp";
|
|
1124
1354
|
|
|
1125
1355
|
interface UserInput {
|
|
1126
1356
|
email: string;
|
|
@@ -1185,13 +1415,12 @@ async function sendVerificationEmail(
|
|
|
1185
1415
|
return Result.Ok(profile);
|
|
1186
1416
|
}
|
|
1187
1417
|
|
|
1188
|
-
// Main registration pipeline
|
|
1418
|
+
// Main registration pipeline using validate + flatMap
|
|
1189
1419
|
async function registerUser(
|
|
1190
1420
|
input: UserInput,
|
|
1191
1421
|
): Promise<Result<UserProfile, string | string[]>> {
|
|
1192
1422
|
const res = await Result.Ok(input)
|
|
1193
1423
|
.validate([
|
|
1194
|
-
// handles both sync and async functions
|
|
1195
1424
|
({ email }) => guardEmail(email),
|
|
1196
1425
|
({ email }) => guardEmailAvailability(email),
|
|
1197
1426
|
({ password }) => guardPassword(password),
|
|
@@ -1227,7 +1456,7 @@ async function main() {
|
|
|
1227
1456
|
}
|
|
1228
1457
|
|
|
1229
1458
|
main();
|
|
1230
|
-
//
|
|
1459
|
+
// Example output:
|
|
1231
1460
|
// Verification email sent to newuser@example.com
|
|
1232
1461
|
// Email: newuser@example.com
|
|
1233
1462
|
// Registration successful!
|