@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
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.asyncGenAdapter() - Async generator with adapter for better type inference
|
|
3
|
+
*
|
|
4
|
+
* asyncGenAdapter() combines asyncGen with an adapter function ($)
|
|
5
|
+
* for improved type inference in complex async workflows.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// BASIC ASYNC GENADAPTER EXAMPLES
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
console.log("=== Result.asyncGenAdapter() Examples ===\n")
|
|
15
|
+
|
|
16
|
+
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
17
|
+
|
|
18
|
+
// Example 1: Simple asyncGenAdapter
|
|
19
|
+
const simple = await Result.asyncGenAdapter(async function* ($) {
|
|
20
|
+
const value = yield* $(Result.Ok(42))
|
|
21
|
+
return value
|
|
22
|
+
})
|
|
23
|
+
console.log("1. Simple asyncGenAdapter:", simple.unwrap()) // 42
|
|
24
|
+
|
|
25
|
+
// Example 2: asyncGenAdapter with Promise<Result>
|
|
26
|
+
const withPromise = await Result.asyncGenAdapter(async function* ($) {
|
|
27
|
+
const value = yield* $(await Promise.resolve(Result.Ok(42)))
|
|
28
|
+
return value
|
|
29
|
+
})
|
|
30
|
+
console.log("2. With Promise<Result>:", withPromise.unwrap()) // 42
|
|
31
|
+
|
|
32
|
+
// Example 3: Multiple yields with adapter
|
|
33
|
+
const multiple = await Result.asyncGenAdapter(async function* ($) {
|
|
34
|
+
const a = yield* $(Result.Ok(5))
|
|
35
|
+
const b = yield* $(await Promise.resolve(Result.Ok(10)))
|
|
36
|
+
const c = yield* $(Result.Ok(15))
|
|
37
|
+
return a + b + c
|
|
38
|
+
})
|
|
39
|
+
console.log("3. Multiple yields:", multiple.unwrap()) // 30
|
|
40
|
+
|
|
41
|
+
// Example 4: asyncGenAdapter improves type inference
|
|
42
|
+
type Error1 = { type: "error1" }
|
|
43
|
+
type Error2 = { type: "error2" }
|
|
44
|
+
|
|
45
|
+
const asyncOp1 = async (): Promise<Result<number, Error1>> => {
|
|
46
|
+
await delay(10)
|
|
47
|
+
return Result.Ok(42)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const asyncOp2 = async (n: number): Promise<Result<number, Error2>> => {
|
|
51
|
+
await delay(10)
|
|
52
|
+
return Result.Ok(n * 2)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const combined = await Result.asyncGenAdapter(async function* ($) {
|
|
56
|
+
const a = yield* $(await asyncOp1())
|
|
57
|
+
const b = yield* $(await asyncOp2(a))
|
|
58
|
+
return b
|
|
59
|
+
})
|
|
60
|
+
// Type is Promise<Result<number, Error1 | Error2>>
|
|
61
|
+
console.log("4. Combined error types:", combined.unwrap()) // 84
|
|
62
|
+
|
|
63
|
+
// Example 5: asyncGenAdapter for API composition
|
|
64
|
+
type ApiError = { status: number; message: string }
|
|
65
|
+
|
|
66
|
+
const fetchUser = async (
|
|
67
|
+
id: number,
|
|
68
|
+
): Promise<Result<{ id: number; name: string }, ApiError>> => {
|
|
69
|
+
await delay(10)
|
|
70
|
+
return Result.Ok({ id, name: `User ${id}` })
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const fetchPosts = async (
|
|
74
|
+
_userId: number,
|
|
75
|
+
): Promise<Result<{ id: number; title: string }[], ApiError>> => {
|
|
76
|
+
await delay(10)
|
|
77
|
+
return Result.Ok([{ id: 1, title: "Post 1" }])
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const fetchSettings = async (
|
|
81
|
+
_userId: number,
|
|
82
|
+
): Promise<Result<{ theme: string }, ApiError>> => {
|
|
83
|
+
await delay(10)
|
|
84
|
+
return Result.Ok({ theme: "dark" })
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const fetchAllUserData = async (userId: number) => {
|
|
88
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
89
|
+
const user = yield* $(await fetchUser(userId))
|
|
90
|
+
const posts = yield* $(await fetchPosts(user.id))
|
|
91
|
+
const settings = yield* $(await fetchSettings(user.id))
|
|
92
|
+
|
|
93
|
+
return { user, posts, settings }
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
const allData = await fetchAllUserData(1)
|
|
97
|
+
console.log("5. Fetch all user data:", allData.unwrap()) // { user: { id: 1, name: "User 1" }, posts: [...], settings: { theme: "dark" } }
|
|
98
|
+
|
|
99
|
+
// Example 6: asyncGenAdapter with async transformation
|
|
100
|
+
const doubleAsync = async (n: number): Promise<number> => {
|
|
101
|
+
await delay(10)
|
|
102
|
+
return n * 2
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const autoAwait = (async () => {
|
|
106
|
+
const gen = Result.asyncGenAdapter(async function* ($) {
|
|
107
|
+
const value = yield* $(Result.Ok(5))
|
|
108
|
+
const doubled = await doubleAsync(value)
|
|
109
|
+
return doubled
|
|
110
|
+
})
|
|
111
|
+
return gen
|
|
112
|
+
})()
|
|
113
|
+
console.log("6. Async transformation:", (await autoAwait).unwrap()) // 10
|
|
114
|
+
|
|
115
|
+
// Example 7: asyncGenAdapter with complex validation
|
|
116
|
+
type ValidationError =
|
|
117
|
+
| { field: "email"; code: "INVALID" | "REQUIRED" }
|
|
118
|
+
| { field: "password"; code: "WEAK" | "REQUIRED" }
|
|
119
|
+
| { field: "age"; code: "TOO_YOUNG" }
|
|
120
|
+
|
|
121
|
+
const validateEmailAsync = async (
|
|
122
|
+
email: string,
|
|
123
|
+
): Promise<Result<string, ValidationError>> => {
|
|
124
|
+
await delay(5)
|
|
125
|
+
if (!email) return Result.Err({ field: "email", code: "REQUIRED" })
|
|
126
|
+
if (!email.includes("@"))
|
|
127
|
+
return Result.Err({ field: "email", code: "INVALID" })
|
|
128
|
+
return Result.Ok(email)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const validatePasswordAsync = async (
|
|
132
|
+
password: string,
|
|
133
|
+
): Promise<Result<string, ValidationError>> => {
|
|
134
|
+
await delay(5)
|
|
135
|
+
if (!password) return Result.Err({ field: "password", code: "REQUIRED" })
|
|
136
|
+
if (password.length < 8)
|
|
137
|
+
return Result.Err({ field: "password", code: "WEAK" })
|
|
138
|
+
return Result.Ok(password)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const validateAgeAsync = async (
|
|
142
|
+
age: number,
|
|
143
|
+
): Promise<Result<number, ValidationError>> => {
|
|
144
|
+
await delay(5)
|
|
145
|
+
if (age < 18) return Result.Err({ field: "age", code: "TOO_YOUNG" })
|
|
146
|
+
return Result.Ok(age)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const registerUserAsync = async (
|
|
150
|
+
email: string,
|
|
151
|
+
password: string,
|
|
152
|
+
age: number,
|
|
153
|
+
) => {
|
|
154
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
155
|
+
const validEmail = yield* $(await validateEmailAsync(email))
|
|
156
|
+
const validPassword = yield* $(await validatePasswordAsync(password))
|
|
157
|
+
const validAge = yield* $(await validateAgeAsync(age))
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
email: validEmail,
|
|
161
|
+
password: validPassword,
|
|
162
|
+
age: validAge,
|
|
163
|
+
registered: true,
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
const registered = await registerUserAsync(
|
|
168
|
+
"user@example.com",
|
|
169
|
+
"password123",
|
|
170
|
+
25,
|
|
171
|
+
)
|
|
172
|
+
console.log("7. Register user:", registered.unwrap()) // { email: "user@example.com", password: "password123", age: 25, registered: true }
|
|
173
|
+
|
|
174
|
+
// Example 8: asyncGenAdapter for transaction workflow
|
|
175
|
+
type TransactionError =
|
|
176
|
+
| { type: "insufficient_funds"; balance: number }
|
|
177
|
+
| { type: "account_not_found" }
|
|
178
|
+
| { type: "network_error" }
|
|
179
|
+
|
|
180
|
+
interface Account {
|
|
181
|
+
id: number
|
|
182
|
+
balance: number
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const getAccountAsync = async (
|
|
186
|
+
id: number,
|
|
187
|
+
): Promise<Result<Account, TransactionError>> => {
|
|
188
|
+
await delay(10)
|
|
189
|
+
if (id === 999) return Result.Err({ type: "account_not_found" })
|
|
190
|
+
return Result.Ok({ id, balance: 100 })
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const debitAsync = async (
|
|
194
|
+
account: Account,
|
|
195
|
+
amount: number,
|
|
196
|
+
): Promise<Result<Account, TransactionError>> => {
|
|
197
|
+
await delay(10)
|
|
198
|
+
if (account.balance < amount) {
|
|
199
|
+
return Result.Err({ type: "insufficient_funds", balance: account.balance })
|
|
200
|
+
}
|
|
201
|
+
return Result.Ok({ ...account, balance: account.balance - amount })
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const creditAsync = async (
|
|
205
|
+
account: Account,
|
|
206
|
+
amount: number,
|
|
207
|
+
): Promise<Result<Account, TransactionError>> => {
|
|
208
|
+
await delay(10)
|
|
209
|
+
return Result.Ok({ ...account, balance: account.balance + amount })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const transferAsync = async (fromId: number, toId: number, amount: number) => {
|
|
213
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
214
|
+
const fromAccount = yield* $(await getAccountAsync(fromId))
|
|
215
|
+
const toAccount = yield* $(await getAccountAsync(toId))
|
|
216
|
+
|
|
217
|
+
const debited = yield* $(await debitAsync(fromAccount, amount))
|
|
218
|
+
const credited = yield* $(await creditAsync(toAccount, amount))
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
from: debited,
|
|
222
|
+
to: credited,
|
|
223
|
+
amount,
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
const transferResult = await transferAsync(1, 2, 50)
|
|
228
|
+
console.log("8. Transfer async:", transferResult.unwrap()) // { from: { id: 1, balance: 50 }, to: { id: 2, balance: 150 }, amount: 50 }
|
|
229
|
+
|
|
230
|
+
// Example 9: asyncGenAdapter with sequential fallback (using orElse)
|
|
231
|
+
const fetchWithRetryAsync = async (
|
|
232
|
+
url: string,
|
|
233
|
+
retries = 3,
|
|
234
|
+
): Promise<Result<string, "fetch_failed">> => {
|
|
235
|
+
for (let i = 0; i < retries; i++) {
|
|
236
|
+
await delay(10)
|
|
237
|
+
if (url === "https://api.example.com/data") {
|
|
238
|
+
return Result.Ok("response data")
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return Result.Err("fetch_failed")
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Fallback pattern using orElse for error recovery
|
|
245
|
+
const fetchWithFallbackAsync = async (
|
|
246
|
+
primaryUrl: string,
|
|
247
|
+
fallbackUrls: string[],
|
|
248
|
+
) => {
|
|
249
|
+
// Try primary first
|
|
250
|
+
let result = await fetchWithRetryAsync(primaryUrl)
|
|
251
|
+
|
|
252
|
+
// Try fallbacks in sequence (orElse is synchronous)
|
|
253
|
+
for (const url of fallbackUrls) {
|
|
254
|
+
if (result.isErr()) {
|
|
255
|
+
result = await fetchWithRetryAsync(url)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return result
|
|
260
|
+
}
|
|
261
|
+
const fallbackResult = await fetchWithFallbackAsync("https://invalid.com", [
|
|
262
|
+
"https://backup.com/data",
|
|
263
|
+
"https://api.example.com/data",
|
|
264
|
+
])
|
|
265
|
+
console.log("9. Fetch with fallback:", fallbackResult.unwrap()) // "response data"
|
|
266
|
+
|
|
267
|
+
// Example 10: asyncGenAdapter for data processing pipeline
|
|
268
|
+
type RawData = { input: string }
|
|
269
|
+
type ParsedData = { value: number }
|
|
270
|
+
type ValidatedData = { value: number; valid: true }
|
|
271
|
+
type EnrichedData = { value: number; valid: true; timestamp: number }
|
|
272
|
+
|
|
273
|
+
const parseAsync = async (
|
|
274
|
+
data: RawData,
|
|
275
|
+
): Promise<Result<ParsedData, "parse_error">> => {
|
|
276
|
+
await delay(5)
|
|
277
|
+
const num = Number(data.input)
|
|
278
|
+
return Number.isNaN(num)
|
|
279
|
+
? Result.Err("parse_error")
|
|
280
|
+
: Result.Ok({ value: num })
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const validateAsync = async (
|
|
284
|
+
data: ParsedData,
|
|
285
|
+
): Promise<Result<ValidatedData, "validation_error">> => {
|
|
286
|
+
await delay(5)
|
|
287
|
+
return data.value > 0
|
|
288
|
+
? Result.Ok({ value: data.value, valid: true })
|
|
289
|
+
: Result.Err("validation_error")
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const enrichAsync = async (
|
|
293
|
+
data: ValidatedData,
|
|
294
|
+
): Promise<Result<EnrichedData, "enrich_error">> => {
|
|
295
|
+
await delay(5)
|
|
296
|
+
return Result.Ok({ ...data, timestamp: Date.now() })
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const processDataPipelineAsync = async (raw: RawData) => {
|
|
300
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
301
|
+
const parsed = yield* $(await parseAsync(raw))
|
|
302
|
+
const validated = yield* $(await validateAsync(parsed))
|
|
303
|
+
const enriched = yield* $(await enrichAsync(validated))
|
|
304
|
+
return enriched
|
|
305
|
+
})
|
|
306
|
+
}
|
|
307
|
+
const pipelineResult = await processDataPipelineAsync({ input: "42" })
|
|
308
|
+
console.log("10. Data pipeline:", pipelineResult.unwrap()) // { value: 42, valid: true, timestamp: ... }
|
|
309
|
+
|
|
310
|
+
// Example 11: asyncGenAdapter with array operations
|
|
311
|
+
const doubleArrayAsync = async (arr: number[]): Promise<number[]> => {
|
|
312
|
+
await delay(5)
|
|
313
|
+
return arr.map((x) => x * 2)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const filterArrayAsync = async (arr: number[]): Promise<number[]> => {
|
|
317
|
+
await delay(5)
|
|
318
|
+
return arr.filter((x) => x > 5)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const sumArrayAsync = async (arr: number[]): Promise<number> => {
|
|
322
|
+
await delay(5)
|
|
323
|
+
return arr.reduce((a, b) => a + b, 0)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const processItemsAsync = async (items: number[]) => {
|
|
327
|
+
const gen = Result.asyncGenAdapter(async function* ($) {
|
|
328
|
+
const arr = yield* $(Result.Ok(items))
|
|
329
|
+
const doubled = await doubleArrayAsync(arr)
|
|
330
|
+
const filtered = await filterArrayAsync(doubled)
|
|
331
|
+
const sum = await sumArrayAsync(filtered)
|
|
332
|
+
return sum
|
|
333
|
+
})
|
|
334
|
+
return gen
|
|
335
|
+
}
|
|
336
|
+
const itemsResult = await processItemsAsync([1, 2, 3, 4, 5])
|
|
337
|
+
console.log("11. Process items:", itemsResult.unwrap()) // 24 (6 + 8 + 10)
|
|
338
|
+
|
|
339
|
+
// Example 12: asyncGenAdapter with conditional logic
|
|
340
|
+
const conditionalAsync = (async () => {
|
|
341
|
+
const gen = Result.asyncGenAdapter(async function* ($) {
|
|
342
|
+
const input = yield* $(Result.Ok(5))
|
|
343
|
+
|
|
344
|
+
if (input > 0) {
|
|
345
|
+
const result = await (async (x: number) => {
|
|
346
|
+
await delay(5)
|
|
347
|
+
return x * 2
|
|
348
|
+
})(input)
|
|
349
|
+
return { value: result, source: "doubled" as const }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return { value: input, source: "original" as const }
|
|
353
|
+
})
|
|
354
|
+
return gen
|
|
355
|
+
})()
|
|
356
|
+
console.log("12. Conditional async:", (await conditionalAsync).unwrap()) // { value: 10, source: "doubled" }
|
|
357
|
+
|
|
358
|
+
// Example 13: asyncGenAdapter for batch operations
|
|
359
|
+
const batchFetchAsync = async (ids: number[]) => {
|
|
360
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
361
|
+
const results: { id: number; name: string }[] = []
|
|
362
|
+
|
|
363
|
+
for (const id of ids) {
|
|
364
|
+
const user = yield* $(await fetchUser(id))
|
|
365
|
+
results.push(user)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
return results
|
|
369
|
+
})
|
|
370
|
+
}
|
|
371
|
+
const batchResult = await batchFetchAsync([1, 2, 3])
|
|
372
|
+
console.log("13. Batch fetch:", batchResult.unwrap()) // [{ id: 1, name: "User 1" }, ...]
|
|
373
|
+
|
|
374
|
+
// Example 14: asyncGenAdapter with parallel-like pattern (sequential but clean)
|
|
375
|
+
const fetchUserProfile = async (userId: number) => {
|
|
376
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
377
|
+
const user = yield* $(await fetchUser(userId))
|
|
378
|
+
const posts = yield* $(await fetchPosts(user.id))
|
|
379
|
+
const settings = yield* $(await fetchSettings(user.id))
|
|
380
|
+
const notifications = yield* $(
|
|
381
|
+
await Promise.resolve(Result.Ok({ unread: 5 })),
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
user,
|
|
386
|
+
posts,
|
|
387
|
+
settings,
|
|
388
|
+
notifications,
|
|
389
|
+
}
|
|
390
|
+
})
|
|
391
|
+
}
|
|
392
|
+
const profile = await fetchUserProfile(1)
|
|
393
|
+
console.log("14. User profile:", profile.unwrap()) // { user: ..., posts: [...], settings: { theme: "dark" }, notifications: { unread: 5 } }
|
|
394
|
+
|
|
395
|
+
// Example 15: asyncGenAdapter with async transformation
|
|
396
|
+
const transformItemsAsync = async (
|
|
397
|
+
items: number[],
|
|
398
|
+
): Promise<Result<number[], "transform_error">> => {
|
|
399
|
+
await delay(5)
|
|
400
|
+
return Result.Ok(items.map((x) => x * 2))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const withToPromise = await Result.asyncGenAdapter(async function* ($) {
|
|
404
|
+
const arr = yield* $(Result.Ok([1, 2, 3]))
|
|
405
|
+
const resolved = yield* $(await transformItemsAsync(arr))
|
|
406
|
+
return resolved
|
|
407
|
+
})
|
|
408
|
+
console.log("15. Async transformation:", withToPromise.unwrap()) // [2, 4, 6]
|
|
409
|
+
|
|
410
|
+
// Example 16: asyncGenAdapter for complex workflow
|
|
411
|
+
type Order = { id: number; items: string[]; total: number }
|
|
412
|
+
type Payment = { orderId: number; amount: number; method: string }
|
|
413
|
+
type Shipment = { orderId: number; tracking: string }
|
|
414
|
+
type Invoice = { orderId: number; paid: boolean }
|
|
415
|
+
|
|
416
|
+
const createOrderAsync = async (
|
|
417
|
+
items: string[],
|
|
418
|
+
): Promise<Result<Order, "order_error">> => {
|
|
419
|
+
await delay(10)
|
|
420
|
+
return Result.Ok({ id: 1, items, total: 100 })
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const processPaymentAsync = async (
|
|
424
|
+
order: Order,
|
|
425
|
+
): Promise<Result<Payment, "payment_error">> => {
|
|
426
|
+
await delay(10)
|
|
427
|
+
return Result.Ok({
|
|
428
|
+
orderId: order.id,
|
|
429
|
+
amount: order.total,
|
|
430
|
+
method: "credit_card",
|
|
431
|
+
})
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const arrangeShipmentAsync = async (
|
|
435
|
+
order: Order,
|
|
436
|
+
): Promise<Result<Shipment, "shipment_error">> => {
|
|
437
|
+
await delay(10)
|
|
438
|
+
return Result.Ok({ orderId: order.id, tracking: "TRACK123" })
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const generateInvoiceAsync = async (
|
|
442
|
+
payment: Payment,
|
|
443
|
+
): Promise<Result<Invoice, "invoice_error">> => {
|
|
444
|
+
await delay(10)
|
|
445
|
+
return Result.Ok({ orderId: payment.orderId, paid: true })
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const completeOrderWorkflow = async (items: string[]) => {
|
|
449
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
450
|
+
const order = yield* $(await createOrderAsync(items))
|
|
451
|
+
const payment = yield* $(await processPaymentAsync(order))
|
|
452
|
+
const shipment = yield* $(await arrangeShipmentAsync(order))
|
|
453
|
+
const invoice = yield* $(await generateInvoiceAsync(payment))
|
|
454
|
+
|
|
455
|
+
return {
|
|
456
|
+
order,
|
|
457
|
+
payment,
|
|
458
|
+
shipment,
|
|
459
|
+
invoice,
|
|
460
|
+
}
|
|
461
|
+
})
|
|
462
|
+
}
|
|
463
|
+
const workflowResult = await completeOrderWorkflow(["item1", "item2"])
|
|
464
|
+
console.log("16. Complete workflow:", workflowResult.unwrap()) // { order: { ... }, payment: { ... }, shipment: { ... }, invoice: { ... } }
|
|
465
|
+
|
|
466
|
+
// Example 17: asyncGenAdapter with error aggregation pattern
|
|
467
|
+
type ConfigError = { key: string; message: string }
|
|
468
|
+
|
|
469
|
+
const fetchConfigAsync = async (
|
|
470
|
+
key: string,
|
|
471
|
+
): Promise<Result<string, ConfigError>> => {
|
|
472
|
+
await delay(5)
|
|
473
|
+
const configs: Record<string, string> = {
|
|
474
|
+
api_key: "secret123",
|
|
475
|
+
timeout: "5000",
|
|
476
|
+
}
|
|
477
|
+
const value = configs[key]
|
|
478
|
+
return value ? Result.Ok(value) : Result.Err({ key, message: "Not found" })
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const fetchAllConfigsAsync = async (keys: string[]) => {
|
|
482
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
483
|
+
const configs: Record<string, string> = {}
|
|
484
|
+
|
|
485
|
+
for (const key of keys) {
|
|
486
|
+
const value = yield* $(await fetchConfigAsync(key))
|
|
487
|
+
configs[key] = value
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return configs
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
const configsResult = await fetchAllConfigsAsync(["api_key", "timeout"])
|
|
494
|
+
console.log("17. Fetch all configs:", configsResult.unwrap()) // { api_key: "secret123", timeout: "5000" }
|
|
495
|
+
|
|
496
|
+
// Example 18: asyncGenAdapter with nested operations
|
|
497
|
+
const nested = (async () => {
|
|
498
|
+
const gen = Result.asyncGenAdapter(async function* ($) {
|
|
499
|
+
const outer = yield* $(Result.Ok(5))
|
|
500
|
+
|
|
501
|
+
// Nested asyncGenAdapter call - returns a Result, so we yield* to flatten it
|
|
502
|
+
const inner = yield* $(
|
|
503
|
+
await Result.asyncGenAdapter(async function* ($) {
|
|
504
|
+
const a = yield* $(Result.Ok(outer))
|
|
505
|
+
const b = await (async (x: number) => {
|
|
506
|
+
await delay(5)
|
|
507
|
+
return x * 2
|
|
508
|
+
})(a)
|
|
509
|
+
return b
|
|
510
|
+
}),
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
return inner
|
|
514
|
+
})
|
|
515
|
+
return gen
|
|
516
|
+
})()
|
|
517
|
+
console.log("18. Nested:", (await nested).unwrap()) // 10
|
|
518
|
+
|
|
519
|
+
// Example 19: asyncGenAdapter vs asyncGen - same result
|
|
520
|
+
const asyncGenResult = await Result.asyncGen(async function* () {
|
|
521
|
+
const a = yield* await Promise.resolve(Result.Ok(1))
|
|
522
|
+
const b = yield* await Promise.resolve(Result.Ok(2))
|
|
523
|
+
return a + b
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
const adapterResult = await Result.asyncGenAdapter(async function* ($) {
|
|
527
|
+
const a = yield* $(await Promise.resolve(Result.Ok(1)))
|
|
528
|
+
const b = yield* $(await Promise.resolve(Result.Ok(2)))
|
|
529
|
+
return a + b
|
|
530
|
+
})
|
|
531
|
+
|
|
532
|
+
console.log("19. asyncGen:", asyncGenResult.unwrap()) // 3
|
|
533
|
+
console.log(" asyncGenAdapter:", adapterResult.unwrap()) // 3
|
|
534
|
+
|
|
535
|
+
// Example 20: asyncGenAdapter for streaming-like pattern
|
|
536
|
+
const processStreamAsync = async (chunks: string[]) => {
|
|
537
|
+
// biome-ignore lint/correctness/useYield: no worries
|
|
538
|
+
return Result.asyncGenAdapter(async function* (_$) {
|
|
539
|
+
// oxlint-disable-next-line require-yield
|
|
540
|
+
let buffer = ""
|
|
541
|
+
|
|
542
|
+
for (const chunk of chunks) {
|
|
543
|
+
await delay(5)
|
|
544
|
+
buffer += chunk
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
return buffer
|
|
548
|
+
})
|
|
549
|
+
}
|
|
550
|
+
const streamResult = await processStreamAsync(["Hello", " ", "World", "!"])
|
|
551
|
+
console.log("20. Process stream:", streamResult.unwrap()) // "Hello World!"
|
|
552
|
+
|
|
553
|
+
console.log("\n=== All asyncGenAdapter examples completed ===")
|