@carbonteq/fp 0.8.2 → 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 +718 -95
- package/dist/errors.cjs +20 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +10 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.mts +10 -0
- package/dist/errors.d.mts.map +1 -0
- package/dist/errors.mjs +17 -0
- package/dist/errors.mjs.map +1 -0
- 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 +28 -7
- package/dist/index.d.cts +11 -5
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +12 -0
- package/dist/match.cjs +294 -3
- package/dist/match.cjs.map +1 -0
- package/dist/match.d.cts +481 -5
- package/dist/match.d.cts.map +1 -0
- package/dist/match.d.mts +481 -0
- package/dist/match.d.mts.map +1 -0
- package/dist/match.mjs +287 -0
- package/dist/match.mjs.map +1 -0
- 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 +806 -4
- package/dist/option.cjs.map +1 -0
- package/dist/option.d.cts +580 -3
- package/dist/option.d.cts.map +1 -0
- package/dist/option.d.mts +580 -0
- package/dist/option.d.mts.map +1 -0
- package/dist/option.mjs +805 -0
- package/dist/option.mjs.map +1 -0
- 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 +1077 -5
- package/dist/result.cjs.map +1 -0
- package/dist/result.d.cts +833 -3
- package/dist/result.d.cts.map +1 -0
- package/dist/result.d.mts +833 -0
- package/dist/result.d.mts.map +1 -0
- package/dist/result.mjs +1077 -0
- package/dist/result.mjs.map +1 -0
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -2
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +15 -0
- package/dist/tuple.d.mts.map +1 -0
- package/dist/{tuple.js → tuple.mjs} +3 -1
- package/dist/tuple.mjs.map +1 -0
- package/dist/unit.cjs +8 -2
- package/dist/unit.cjs.map +1 -0
- package/dist/unit.d.cts +8 -2
- package/dist/unit.d.cts.map +1 -0
- package/dist/unit.d.mts +8 -0
- package/dist/unit.d.mts.map +1 -0
- package/dist/unit.mjs +7 -0
- package/dist/unit.mjs.map +1 -0
- package/dist/utils.cjs +24 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +14 -0
- package/dist/utils.d.cts.map +1 -0
- package/dist/utils.d.mts +14 -0
- package/dist/utils.d.mts.map +1 -0
- package/dist/utils.mjs +20 -0
- package/dist/utils.mjs.map +1 -0
- 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 +120 -48
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/index.d.ts +0 -5
- package/dist/index.js +0 -6
- package/dist/match-BQP0RNSk.js +0 -13
- package/dist/match-BQP0RNSk.js.map +0 -1
- package/dist/match-COIWq-e8.d.cts +0 -18
- package/dist/match-COIWq-e8.d.cts.map +0 -1
- package/dist/match-DXKW7ym5.d.ts +0 -18
- package/dist/match-DXKW7ym5.d.ts.map +0 -1
- package/dist/match-DyAuOeqx.cjs +0 -25
- package/dist/match-DyAuOeqx.cjs.map +0 -1
- package/dist/match.d.ts +0 -5
- package/dist/match.js +0 -3
- package/dist/option-8_eiz02z.d.cts +0 -45
- package/dist/option-8_eiz02z.d.cts.map +0 -1
- package/dist/option-Be_DXVE6.js +0 -181
- package/dist/option-Be_DXVE6.js.map +0 -1
- package/dist/option-CoelyMEg.d.ts +0 -45
- package/dist/option-CoelyMEg.d.ts.map +0 -1
- package/dist/option-DHCdfOco.cjs +0 -193
- package/dist/option-DHCdfOco.cjs.map +0 -1
- package/dist/option.d.ts +0 -3
- package/dist/option.js +0 -4
- package/dist/result-CdGWA5IL.js +0 -318
- package/dist/result-CdGWA5IL.js.map +0 -1
- package/dist/result-DsVjSFnO.d.ts +0 -132
- package/dist/result-DsVjSFnO.d.ts.map +0 -1
- package/dist/result-Dy_C5dC6.d.cts +0 -132
- package/dist/result-Dy_C5dC6.d.cts.map +0 -1
- package/dist/result-nuhyCRyu.cjs +0 -336
- package/dist/result-nuhyCRyu.cjs.map +0 -1
- package/dist/result.d.ts +0 -3
- package/dist/result.js +0 -4
- package/dist/tuple.d.ts +0 -12
- package/dist/tuple.d.ts.map +0 -1
- package/dist/tuple.js.map +0 -1
- package/dist/unit-CnjFzJN1.cjs +0 -12
- package/dist/unit-CnjFzJN1.cjs.map +0 -1
- package/dist/unit-CoBLIJFc.d.ts +0 -9
- package/dist/unit-CoBLIJFc.d.ts.map +0 -1
- package/dist/unit-D0y_qAUW.d.cts +0 -9
- package/dist/unit-D0y_qAUW.d.cts.map +0 -1
- package/dist/unit-udy5j53P.js +0 -6
- package/dist/unit-udy5j53P.js.map +0 -1
- package/dist/unit.d.ts +0 -2
- package/dist/unit.js +0 -3
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Option.asyncGenAdapter() - Async generator with adapter
|
|
3
|
+
*
|
|
4
|
+
* Option.asyncGenAdapter() provides the same imperative-style async code
|
|
5
|
+
* as asyncGen(), but with an adapter function ($) for improved type inference
|
|
6
|
+
* when working with Promise<Option<T>> and Option<Promise<T>>.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC ASYNC GENADAPTER EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Option.asyncGenAdapter() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Simple asyncGenAdapter with single yield
|
|
18
|
+
const simple = await Option.asyncGenAdapter(async function* ($) {
|
|
19
|
+
const value = yield* $(Option.Some(42))
|
|
20
|
+
return value
|
|
21
|
+
})
|
|
22
|
+
console.log("1. Simple asyncGenAdapter:", simple.unwrap()) // 42
|
|
23
|
+
|
|
24
|
+
// Example 2: Multiple yields with async operations
|
|
25
|
+
const multiple = await Option.asyncGenAdapter(async function* ($) {
|
|
26
|
+
const a = yield* $(Option.Some(5))
|
|
27
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
28
|
+
const b = yield* $(Option.Some(10))
|
|
29
|
+
return a + b
|
|
30
|
+
})
|
|
31
|
+
console.log("2. Multiple yields with delay:", multiple.unwrap()) // 15
|
|
32
|
+
|
|
33
|
+
// Example 3: Short-circuit on first None
|
|
34
|
+
const shortCircuit = await Option.asyncGenAdapter(async function* ($) {
|
|
35
|
+
const a = yield* $(Option.Some(5))
|
|
36
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
37
|
+
const b = yield* $(Option.None) // This causes None to return
|
|
38
|
+
const c = yield* $(Option.Some(10)) // This is never reached
|
|
39
|
+
return a + b + c
|
|
40
|
+
})
|
|
41
|
+
console.log("3. Short-circuit:", shortCircuit._tag) // "None"
|
|
42
|
+
|
|
43
|
+
// Example 4: asyncGenAdapter with Promise<Option<T>>
|
|
44
|
+
const fetchValue = async (key: string): Promise<Option<number>> => {
|
|
45
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
46
|
+
if (key === "valid") return Option.Some(42)
|
|
47
|
+
return Option.None
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const withFetch = await Option.asyncGenAdapter(async function* ($) {
|
|
51
|
+
const a = yield* $(await fetchValue("valid"))
|
|
52
|
+
const b = yield* $(await fetchValue("valid"))
|
|
53
|
+
return a + b
|
|
54
|
+
})
|
|
55
|
+
console.log("4. With Promise<Option>:", withFetch.unwrap()) // 84
|
|
56
|
+
|
|
57
|
+
// Example 5: asyncGenAdapter with Option<Promise<T>>
|
|
58
|
+
const autoAwait = await Option.asyncGenAdapter(async function* ($) {
|
|
59
|
+
// Option<Promise<number>> - inner promise is auto-awaited
|
|
60
|
+
const value = yield* $(Option.Some(Promise.resolve(42)))
|
|
61
|
+
return value * 2
|
|
62
|
+
})
|
|
63
|
+
console.log("5. Auto-await inner promise:", autoAwait.unwrap()) // 84
|
|
64
|
+
|
|
65
|
+
// Example 6: Mixed Promise<Option> and Option<Promise>
|
|
66
|
+
const mixed = await Option.asyncGenAdapter(async function* ($) {
|
|
67
|
+
const a = yield* $(Option.Some(5)) // sync
|
|
68
|
+
const b = yield* $(await Promise.resolve(Option.Some(10))) // Promise<Option>
|
|
69
|
+
const c = yield* $(Option.Some(Promise.resolve(15))) // Option<Promise>
|
|
70
|
+
return a + b + c
|
|
71
|
+
})
|
|
72
|
+
console.log("6. Mixed sync/async:", mixed.unwrap()) // 30
|
|
73
|
+
|
|
74
|
+
// Example 7: asyncGenAdapter for API composition
|
|
75
|
+
type UserId = number
|
|
76
|
+
type User = { id: UserId; name: string }
|
|
77
|
+
type PostId = number
|
|
78
|
+
type Post = { id: PostId; authorId: UserId; title: string }
|
|
79
|
+
|
|
80
|
+
const getUserAsync = async (id: UserId): Promise<Option<User>> => {
|
|
81
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
82
|
+
return Option.Some({ id, name: `User ${id}` })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const getPostAsync = async (id: PostId): Promise<Option<Post>> => {
|
|
86
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
87
|
+
return Option.Some({ id, authorId: 1, title: `Post ${id}` })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const getPostWithAuthorAsync = async (postId: PostId) => {
|
|
91
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
92
|
+
const post = yield* $(await getPostAsync(postId))
|
|
93
|
+
const author = yield* $(await getUserAsync(post.authorId))
|
|
94
|
+
return { post, author }
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
console.log("7. API composition:", (await getPostWithAuthorAsync(101)).unwrap())
|
|
98
|
+
|
|
99
|
+
// Example 8: asyncGenAdapter for complex async validation
|
|
100
|
+
const validateEmailAsync = async (email: string): Promise<Option<string>> => {
|
|
101
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
102
|
+
return email.includes("@") ? Option.Some(email) : Option.None
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const validatePasswordAsync = async (
|
|
106
|
+
password: string,
|
|
107
|
+
): Promise<Option<string>> => {
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
109
|
+
return password.length >= 8 ? Option.Some(password) : Option.None
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const validateAgeAsync = async (age: number): Promise<Option<number>> => {
|
|
113
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
114
|
+
return age >= 18 ? Option.Some(age) : Option.None
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const validateUserAsync = async (data: {
|
|
118
|
+
email: string
|
|
119
|
+
password: string
|
|
120
|
+
age: number
|
|
121
|
+
}) => {
|
|
122
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
123
|
+
const validEmail = yield* $(await validateEmailAsync(data.email))
|
|
124
|
+
const validPassword = yield* $(await validatePasswordAsync(data.password))
|
|
125
|
+
const validAge = yield* $(await validateAgeAsync(data.age))
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
email: validEmail,
|
|
129
|
+
password: validPassword,
|
|
130
|
+
age: validAge,
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
console.log(
|
|
135
|
+
"8. Valid user:",
|
|
136
|
+
(
|
|
137
|
+
await validateUserAsync({
|
|
138
|
+
email: "test@example.com",
|
|
139
|
+
password: "password123",
|
|
140
|
+
age: 25,
|
|
141
|
+
})
|
|
142
|
+
).unwrap(),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
// Example 9: asyncGenAdapter for transaction workflows
|
|
146
|
+
type Account = { balance: number }
|
|
147
|
+
type TransferResult = { fromBalance: number; toBalance: number }
|
|
148
|
+
|
|
149
|
+
const getAccountAsync = async (id: number): Promise<Option<Account>> => {
|
|
150
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
151
|
+
const accounts = new Map<number, Account>([
|
|
152
|
+
[1, { balance: 100 }],
|
|
153
|
+
[2, { balance: 50 }],
|
|
154
|
+
])
|
|
155
|
+
return Option.fromNullable(accounts.get(id))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const debitAsync = async (
|
|
159
|
+
account: Account,
|
|
160
|
+
amount: number,
|
|
161
|
+
): Promise<Option<Account>> => {
|
|
162
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
163
|
+
return account.balance >= amount
|
|
164
|
+
? Option.Some({ balance: account.balance - amount })
|
|
165
|
+
: Option.None
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const creditAsync = async (
|
|
169
|
+
account: Account,
|
|
170
|
+
amount: number,
|
|
171
|
+
): Promise<Option<Account>> => {
|
|
172
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
173
|
+
return Option.Some({ balance: account.balance + amount })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const transferAsync = async (fromId: number, toId: number, amount: number) => {
|
|
177
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
178
|
+
const fromAccount = yield* $(await getAccountAsync(fromId))
|
|
179
|
+
const toAccount = yield* $(await getAccountAsync(toId))
|
|
180
|
+
|
|
181
|
+
const debited = yield* $(await debitAsync(fromAccount, amount))
|
|
182
|
+
const credited = yield* $(await creditAsync(toAccount, amount))
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
fromBalance: debited.balance,
|
|
186
|
+
toBalance: credited.balance,
|
|
187
|
+
} as TransferResult
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
console.log("9. Transfer:", (await transferAsync(1, 2, 30)).unwrap()) // { fromBalance: 70, toBalance: 80 }
|
|
191
|
+
|
|
192
|
+
// Example 10: asyncGenAdapter demonstrating proper async fallback
|
|
193
|
+
// Note: For retry logic, it's often better to handle retries outside the generator
|
|
194
|
+
// since None values cause immediate short-circuiting
|
|
195
|
+
const fetchWithFallbackAsync = async (
|
|
196
|
+
url: string,
|
|
197
|
+
fallback: string,
|
|
198
|
+
): Promise<string> => {
|
|
199
|
+
const tryFetchAsync = async (attempt: number): Promise<Option<string>> => {
|
|
200
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
201
|
+
// Simulate success on 3rd attempt
|
|
202
|
+
if (attempt >= 3) {
|
|
203
|
+
return Option.Some(`Data from ${url} (attempt ${attempt})`)
|
|
204
|
+
}
|
|
205
|
+
return Option.None // Simulate failure
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Manual retry loop outside asyncGenAdapter
|
|
209
|
+
for (let i = 1; i <= 3; i++) {
|
|
210
|
+
const result = await tryFetchAsync(i)
|
|
211
|
+
if (result.isSome()) {
|
|
212
|
+
return result.unwrap()
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return fallback // Return fallback if all attempts fail
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
console.log(
|
|
219
|
+
"10. Retry with fallback:",
|
|
220
|
+
await fetchWithFallbackAsync("/api/data", "fallback data"),
|
|
221
|
+
) // Should succeed on 3rd attempt
|
|
222
|
+
|
|
223
|
+
// Example 11: asyncGenAdapter for data processing pipelines
|
|
224
|
+
type RawData = { value: string }
|
|
225
|
+
type ParsedData = { value: number }
|
|
226
|
+
type ValidatedData = { value: number; valid: true }
|
|
227
|
+
type EnrichedData = { value: number; valid: true; timestamp: number }
|
|
228
|
+
|
|
229
|
+
const parseAsync = async (data: RawData): Promise<Option<ParsedData>> => {
|
|
230
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
231
|
+
const num = Number(data.value)
|
|
232
|
+
return Number.isNaN(num) ? Option.None : Option.Some({ value: num })
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const validateAsync = async (
|
|
236
|
+
data: ParsedData,
|
|
237
|
+
): Promise<Option<ValidatedData>> => {
|
|
238
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
239
|
+
return data.value > 0
|
|
240
|
+
? Option.Some({ value: data.value, valid: true })
|
|
241
|
+
: Option.None
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const enrichAsync = async (
|
|
245
|
+
data: ValidatedData,
|
|
246
|
+
): Promise<Option<EnrichedData>> => {
|
|
247
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
248
|
+
return Option.Some({ ...data, timestamp: Date.now() })
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const processPipelineAsync = async (raw: RawData) => {
|
|
252
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
253
|
+
const parsed = yield* $(await parseAsync(raw))
|
|
254
|
+
const validated = yield* $(await validateAsync(parsed))
|
|
255
|
+
const enriched = yield* $(await enrichAsync(validated))
|
|
256
|
+
return enriched
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
console.log(
|
|
260
|
+
"11. Processing pipeline:",
|
|
261
|
+
(await processPipelineAsync({ value: "42" })).unwrap(),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
// Example 12: asyncGenAdapter for batch operations
|
|
265
|
+
const fetchItemAsync = async (
|
|
266
|
+
id: number,
|
|
267
|
+
): Promise<Option<{ id: number; name: string }>> => {
|
|
268
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
269
|
+
return id > 0 ? Option.Some({ id, name: `Item ${id}` }) : Option.None
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const fetchBatchAsync = async (ids: number[]) => {
|
|
273
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
274
|
+
const items = []
|
|
275
|
+
for (const id of ids) {
|
|
276
|
+
const item = yield* $(await fetchItemAsync(id))
|
|
277
|
+
items.push(item)
|
|
278
|
+
}
|
|
279
|
+
return items
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
console.log(
|
|
283
|
+
"12. Batch operations:",
|
|
284
|
+
(await fetchBatchAsync([1, 2, 3])).unwrap(),
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
// Example 13: asyncGenAdapter for parallel-like patterns (sequential)
|
|
288
|
+
const fetchMultipleAsync = async (...ids: number[]) => {
|
|
289
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
290
|
+
const results = []
|
|
291
|
+
for (const id of ids) {
|
|
292
|
+
const result = yield* $(await fetchItemAsync(id))
|
|
293
|
+
results.push(result)
|
|
294
|
+
}
|
|
295
|
+
return results
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
console.log(
|
|
299
|
+
"13. Multiple fetches:",
|
|
300
|
+
(await fetchMultipleAsync(1, 2, 3)).unwrap(),
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
// Example 14: asyncGenAdapter with async transformation
|
|
304
|
+
const transformItemsAsync = async (
|
|
305
|
+
items: number[],
|
|
306
|
+
): Promise<Option<number[]>> => {
|
|
307
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
308
|
+
return Option.Some(items.map((n) => n * 2))
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const toPromiseExample = await Option.asyncGenAdapter(async function* ($) {
|
|
312
|
+
const arr = yield* $(Option.Some([1, 2, 3]))
|
|
313
|
+
const items = yield* $(await transformItemsAsync(arr))
|
|
314
|
+
return items.reduce((sum, n) => sum + n, 0)
|
|
315
|
+
})
|
|
316
|
+
console.log("14. Async transformation:", toPromiseExample.unwrap()) // 12
|
|
317
|
+
|
|
318
|
+
// Example 15: asyncGenAdapter for complex workflows
|
|
319
|
+
type Order = { id: number; total: number }
|
|
320
|
+
type Payment = { orderId: number; amount: number }
|
|
321
|
+
type Shipment = { orderId: number; tracking: string }
|
|
322
|
+
type Invoice = { orderId: number; paymentId: number }
|
|
323
|
+
|
|
324
|
+
const fetchOrderAsync = async (orderId: number): Promise<Option<Order>> => {
|
|
325
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
326
|
+
return Option.Some({ id: orderId, total: 100 })
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const processPaymentAsync = async (order: Order): Promise<Option<Payment>> => {
|
|
330
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
331
|
+
return Option.Some({ orderId: order.id, amount: order.total })
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const arrangeShipmentAsync = async (
|
|
335
|
+
payment: Payment,
|
|
336
|
+
): Promise<Option<Shipment>> => {
|
|
337
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
338
|
+
return Option.Some({ orderId: payment.orderId, tracking: "TRACK-123" })
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const generateInvoiceAsync = async (
|
|
342
|
+
shipment: Shipment,
|
|
343
|
+
): Promise<Option<Invoice>> => {
|
|
344
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
345
|
+
return Option.Some({ orderId: shipment.orderId, paymentId: 56789 })
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const processOrderFullAsync = async (orderId: number) => {
|
|
349
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
350
|
+
const order = yield* $(await fetchOrderAsync(orderId))
|
|
351
|
+
const payment = yield* $(await processPaymentAsync(order))
|
|
352
|
+
const shipment = yield* $(await arrangeShipmentAsync(payment))
|
|
353
|
+
const invoice = yield* $(await generateInvoiceAsync(shipment))
|
|
354
|
+
|
|
355
|
+
return { order, payment, shipment, invoice }
|
|
356
|
+
})
|
|
357
|
+
}
|
|
358
|
+
console.log(
|
|
359
|
+
"15. Full order workflow:",
|
|
360
|
+
(await processOrderFullAsync(1)).unwrap(),
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
// Example 16: asyncGenAdapter with conditional logic
|
|
364
|
+
const conditionalAsync = await Option.asyncGenAdapter(async function* ($) {
|
|
365
|
+
const input = yield* $(Option.Some(5))
|
|
366
|
+
if (input > 0) {
|
|
367
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
368
|
+
return input * 2
|
|
369
|
+
}
|
|
370
|
+
return input
|
|
371
|
+
})
|
|
372
|
+
console.log("16. Conditional async:", conditionalAsync.unwrap()) // 10
|
|
373
|
+
|
|
374
|
+
// Example 17: asyncGenAdapter with error recovery
|
|
375
|
+
const riskyOperationAsync = async (value: number): Promise<Option<number>> => {
|
|
376
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
377
|
+
// Simulate 50% failure rate
|
|
378
|
+
return Math.random() > 0.5 ? Option.Some(value * 2) : Option.None
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const withRecoveryAsync = async (value: number) => {
|
|
382
|
+
const opt = await Option.asyncGenAdapter(async function* ($) {
|
|
383
|
+
const result = yield* $(await riskyOperationAsync(value))
|
|
384
|
+
return result
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
return opt.unwrapOr(value) // Fallback to original value
|
|
388
|
+
}
|
|
389
|
+
console.log("17. With recovery (may vary):", await withRecoveryAsync(5)) // Either 10 or 5
|
|
390
|
+
|
|
391
|
+
// Example 18: asyncGenAdapter for nested operations
|
|
392
|
+
const nestedAsync = await Option.asyncGenAdapter(async function* ($) {
|
|
393
|
+
const outer = yield* $(Option.Some(5))
|
|
394
|
+
|
|
395
|
+
const inner = await Option.asyncGenAdapter(async function* ($) {
|
|
396
|
+
const doubled = yield* $(Option.Some(outer * 2))
|
|
397
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
398
|
+
const tripled = yield* $(Option.Some(outer * 3))
|
|
399
|
+
return { doubled, tripled }
|
|
400
|
+
})
|
|
401
|
+
|
|
402
|
+
return yield* $(inner)
|
|
403
|
+
})
|
|
404
|
+
console.log("18. Nested operations:", nestedAsync.unwrap()) // { doubled: 10, tripled: 15 }
|
|
405
|
+
|
|
406
|
+
// Example 19: asyncGenAdapter with streaming-like patterns
|
|
407
|
+
type StreamItem = { index: number; value: string }
|
|
408
|
+
const streamItemsAsync = async function* (): AsyncGenerator<
|
|
409
|
+
Option<StreamItem>
|
|
410
|
+
> {
|
|
411
|
+
const items = ["a", "b", "c"]
|
|
412
|
+
for (let i = 0; i < items.length; i++) {
|
|
413
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
414
|
+
// biome-ignore lint/style/noNonNullAssertion: no need
|
|
415
|
+
yield Option.Some({ index: i, value: items[i]! })
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const processStreamAsync = async () => {
|
|
420
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
421
|
+
const results = []
|
|
422
|
+
for await (const item of streamItemsAsync()) {
|
|
423
|
+
const value = yield* $(item)
|
|
424
|
+
results.push(value)
|
|
425
|
+
}
|
|
426
|
+
return results
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
console.log("19. Stream processing:", (await processStreamAsync()).unwrap()) // [{ index: 0, value: "a" }, ...]
|
|
430
|
+
|
|
431
|
+
// Example 20: asyncGenAdapter for aggregating data
|
|
432
|
+
const fetchMetricAsync = async (name: string): Promise<Option<number>> => {
|
|
433
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
434
|
+
const metrics: Record<string, number> = {
|
|
435
|
+
cpu: 75,
|
|
436
|
+
memory: 60,
|
|
437
|
+
disk: 45,
|
|
438
|
+
}
|
|
439
|
+
return Option.fromNullable(metrics[name])
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const getAverageMetricAsync = async (...names: string[]) => {
|
|
443
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
444
|
+
let sum = 0
|
|
445
|
+
let count = 0
|
|
446
|
+
|
|
447
|
+
for (const name of names) {
|
|
448
|
+
const value = yield* $(await fetchMetricAsync(name))
|
|
449
|
+
sum += value
|
|
450
|
+
count++
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
return count > 0 ? sum / count : 0
|
|
454
|
+
})
|
|
455
|
+
}
|
|
456
|
+
console.log(
|
|
457
|
+
"20. Average metric:",
|
|
458
|
+
(await getAverageMetricAsync("cpu", "memory", "disk")).unwrap(),
|
|
459
|
+
) // 60
|
|
460
|
+
|
|
461
|
+
// Example 21: asyncGenAdapter comparing with asyncGen
|
|
462
|
+
console.log("\n=== asyncGen vs asyncGenAdapter Comparison ===\n")
|
|
463
|
+
|
|
464
|
+
console.log("asyncGen:")
|
|
465
|
+
console.log(" - yield* Option.Some(value)")
|
|
466
|
+
console.log(" - yield* await Promise<Option<T>>")
|
|
467
|
+
console.log(" - Auto-awaits Option<Promise<T>>")
|
|
468
|
+
|
|
469
|
+
console.log("\nasyncGenAdapter:")
|
|
470
|
+
console.log(" - yield* $(Option.Some(value))")
|
|
471
|
+
console.log(" - yield* $(await Promise<Option<T>>)")
|
|
472
|
+
console.log(" - yield* $(Option<Promise<T>>)")
|
|
473
|
+
console.log(" - Better type inference")
|
|
474
|
+
console.log(" - Adapter ($) makes yields explicit")
|
|
475
|
+
|
|
476
|
+
console.log("\nBoth support:")
|
|
477
|
+
console.log(" - Mixed sync/async operations")
|
|
478
|
+
console.log(" - Automatic None short-circuiting")
|
|
479
|
+
console.log(" - Promise<Option<T>> and Option<Promise<T>>")
|
|
480
|
+
|
|
481
|
+
// Example 22: asyncGenAdapter with complex state management
|
|
482
|
+
type State = {
|
|
483
|
+
users: number
|
|
484
|
+
posts: number
|
|
485
|
+
comments: number
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const fetchUsersCountAsync = async (): Promise<Option<number>> => {
|
|
489
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
490
|
+
return Option.Some(100)
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const fetchPostsCountAsync = async (): Promise<Option<number>> => {
|
|
494
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
495
|
+
return Option.Some(500)
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const fetchCommentsCountAsync = async (): Promise<Option<number>> => {
|
|
499
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
500
|
+
return Option.Some(2000)
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const buildDashboardStateAsync = async () => {
|
|
504
|
+
return await Option.asyncGenAdapter(async function* ($) {
|
|
505
|
+
const users = yield* $(await fetchUsersCountAsync())
|
|
506
|
+
const posts = yield* $(await fetchPostsCountAsync())
|
|
507
|
+
const comments = yield* $(await fetchCommentsCountAsync())
|
|
508
|
+
|
|
509
|
+
return { users, posts, comments } as State
|
|
510
|
+
})
|
|
511
|
+
}
|
|
512
|
+
console.log("22. Dashboard state:", (await buildDashboardStateAsync()).unwrap()) // { users: 100, posts: 500, comments: 2000 }
|
|
513
|
+
|
|
514
|
+
console.log("\n=== All asyncGenAdapter examples completed ===")
|