@carbonteq/fp 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +286 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1266 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +46 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +237 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +241 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +50 -18
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simple Sync Workflow - Process Grocery List Details
|
|
3
|
+
*
|
|
4
|
+
* This example shows different styles of implementing the same workflow:
|
|
5
|
+
* 1. flatMap chain style
|
|
6
|
+
* 2. Result.gen style (simplified)
|
|
7
|
+
* 3. Result.genAdapter style (with adapter for better type inference)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
11
|
+
import {
|
|
12
|
+
calculateDetailedStats,
|
|
13
|
+
ensureListIsActive,
|
|
14
|
+
fetchUserById,
|
|
15
|
+
type GroceryListDetails,
|
|
16
|
+
type GroceryListEntity,
|
|
17
|
+
type ItemEntity,
|
|
18
|
+
mockGroceryList,
|
|
19
|
+
mockItems,
|
|
20
|
+
mockUser,
|
|
21
|
+
type UserEntity,
|
|
22
|
+
validateItems,
|
|
23
|
+
} from "./shared-domain"
|
|
24
|
+
|
|
25
|
+
console.log("=== Simple Sync Workflow: Process Grocery List Details ===\n")
|
|
26
|
+
|
|
27
|
+
// ============================================================================
|
|
28
|
+
// STYLE 1: flatMap chain style
|
|
29
|
+
// ============================================================================
|
|
30
|
+
|
|
31
|
+
function processListDetailsUsingFlatMap(
|
|
32
|
+
list: GroceryListEntity,
|
|
33
|
+
owner: UserEntity,
|
|
34
|
+
items: ItemEntity[],
|
|
35
|
+
): GroceryListDetails | never {
|
|
36
|
+
const r = list
|
|
37
|
+
.ensureIsOwner(owner)
|
|
38
|
+
.map((_) => list.serialize())
|
|
39
|
+
.zip((_) => owner.serialize())
|
|
40
|
+
.map(([listEncoded, ownerEncoded]) => {
|
|
41
|
+
const itemsEncoded = items.map((item) => item.serialize())
|
|
42
|
+
return {
|
|
43
|
+
owner: ownerEncoded,
|
|
44
|
+
list: listEncoded,
|
|
45
|
+
items: itemsEncoded,
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
.map(({ list, owner, items: itemsSerialized }) => {
|
|
49
|
+
const stats = calculateDetailedStats(items)
|
|
50
|
+
return {
|
|
51
|
+
...list,
|
|
52
|
+
items: itemsSerialized,
|
|
53
|
+
owner,
|
|
54
|
+
stats,
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
return r.unwrap()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Test flatMap style
|
|
62
|
+
console.log("1. flatMap chain style:")
|
|
63
|
+
const flatMapResult = processListDetailsUsingFlatMap(
|
|
64
|
+
mockGroceryList,
|
|
65
|
+
mockUser,
|
|
66
|
+
mockItems,
|
|
67
|
+
)
|
|
68
|
+
console.log(" Owner:", flatMapResult.owner.name)
|
|
69
|
+
console.log(" Items:", flatMapResult.items.length)
|
|
70
|
+
console.log(" Stats:", flatMapResult.stats)
|
|
71
|
+
|
|
72
|
+
// ============================================================================
|
|
73
|
+
// STYLE 2: Result.gen style (simplified, no adapter)
|
|
74
|
+
// ============================================================================
|
|
75
|
+
|
|
76
|
+
function processListDetailsUsingGen(
|
|
77
|
+
list: GroceryListEntity,
|
|
78
|
+
owner: UserEntity,
|
|
79
|
+
items: ItemEntity[],
|
|
80
|
+
): GroceryListDetails | never {
|
|
81
|
+
const r = Result.gen(function* () {
|
|
82
|
+
// Step 1: Ensure ownership
|
|
83
|
+
yield* list.ensureIsOwner(owner)
|
|
84
|
+
|
|
85
|
+
// Step 2: Serialize data
|
|
86
|
+
const listEncoded = list.serialize()
|
|
87
|
+
const ownerEncoded = owner.serialize()
|
|
88
|
+
const itemsEncoded = items.map((item) => item.serialize())
|
|
89
|
+
|
|
90
|
+
// Step 3: Calculate stats
|
|
91
|
+
const stats = calculateDetailedStats(items)
|
|
92
|
+
|
|
93
|
+
// Step 4: Return combined result
|
|
94
|
+
return {
|
|
95
|
+
id: listEncoded.id,
|
|
96
|
+
name: listEncoded.name,
|
|
97
|
+
description: listEncoded.description,
|
|
98
|
+
active: listEncoded.active,
|
|
99
|
+
owner: ownerEncoded,
|
|
100
|
+
items: itemsEncoded,
|
|
101
|
+
stats,
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
return r.unwrap()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Test gen style
|
|
109
|
+
console.log("\n2. Result.gen style:")
|
|
110
|
+
const genResult = processListDetailsUsingGen(
|
|
111
|
+
mockGroceryList,
|
|
112
|
+
mockUser,
|
|
113
|
+
mockItems,
|
|
114
|
+
)
|
|
115
|
+
console.log(" Owner:", genResult.owner.name)
|
|
116
|
+
console.log(" Items:", genResult.items.length)
|
|
117
|
+
console.log(" Stats:", genResult.stats)
|
|
118
|
+
|
|
119
|
+
// ============================================================================
|
|
120
|
+
// STYLE 3: Result.genAdapter style (with adapter)
|
|
121
|
+
// ============================================================================
|
|
122
|
+
|
|
123
|
+
function processListDetailsUsingGenAdapter(
|
|
124
|
+
list: GroceryListEntity,
|
|
125
|
+
owner: UserEntity,
|
|
126
|
+
items: ItemEntity[],
|
|
127
|
+
): GroceryListDetails | never {
|
|
128
|
+
const r = Result.genAdapter(function* ($) {
|
|
129
|
+
// Step 1: Ensure ownership
|
|
130
|
+
yield* $(list.ensureIsOwner(owner))
|
|
131
|
+
|
|
132
|
+
// Step 2: Serialize data
|
|
133
|
+
const listEncoded = list.serialize()
|
|
134
|
+
const ownerEncoded = owner.serialize()
|
|
135
|
+
const itemsEncoded = items.map((item) => item.serialize())
|
|
136
|
+
|
|
137
|
+
// Step 3: Calculate stats
|
|
138
|
+
const stats = calculateDetailedStats(items)
|
|
139
|
+
|
|
140
|
+
// Step 4: Return combined result
|
|
141
|
+
return {
|
|
142
|
+
id: listEncoded.id,
|
|
143
|
+
name: listEncoded.name,
|
|
144
|
+
description: listEncoded.description,
|
|
145
|
+
active: listEncoded.active,
|
|
146
|
+
owner: ownerEncoded,
|
|
147
|
+
items: itemsEncoded,
|
|
148
|
+
stats,
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
return r.unwrap()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Test genAdapter style
|
|
156
|
+
console.log("\n3. Result.genAdapter style:")
|
|
157
|
+
const genAdapterResult = processListDetailsUsingGenAdapter(
|
|
158
|
+
mockGroceryList,
|
|
159
|
+
mockUser,
|
|
160
|
+
mockItems,
|
|
161
|
+
)
|
|
162
|
+
console.log(" Owner:", genAdapterResult.owner.name)
|
|
163
|
+
console.log(" Items:", genAdapterResult.items.length)
|
|
164
|
+
console.log(" Stats:", genAdapterResult.stats)
|
|
165
|
+
|
|
166
|
+
// ============================================================================
|
|
167
|
+
// COMPARISON: Multi-step validation
|
|
168
|
+
// ============================================================================
|
|
169
|
+
|
|
170
|
+
console.log("\n=== Multi-step Validation Comparison ===\n")
|
|
171
|
+
|
|
172
|
+
// flatMap version
|
|
173
|
+
function processWithValidationsFlatMap(
|
|
174
|
+
list: GroceryListEntity,
|
|
175
|
+
owner: UserEntity,
|
|
176
|
+
items: ItemEntity[],
|
|
177
|
+
) {
|
|
178
|
+
return list
|
|
179
|
+
.ensureIsOwner(owner)
|
|
180
|
+
.flatMap((_) => ensureListIsActive(list))
|
|
181
|
+
.flatMap((_) => validateItems(items))
|
|
182
|
+
.map((validItems) => {
|
|
183
|
+
const stats = calculateDetailedStats(validItems)
|
|
184
|
+
return {
|
|
185
|
+
...list.serialize(),
|
|
186
|
+
owner: owner.serialize(),
|
|
187
|
+
items: validItems.map((i) => i.serialize()),
|
|
188
|
+
stats,
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// gen version
|
|
194
|
+
function processWithValidationsGen(
|
|
195
|
+
list: GroceryListEntity,
|
|
196
|
+
owner: UserEntity,
|
|
197
|
+
items: ItemEntity[],
|
|
198
|
+
) {
|
|
199
|
+
return Result.gen(function* () {
|
|
200
|
+
yield* list.ensureIsOwner(owner)
|
|
201
|
+
yield* ensureListIsActive(list)
|
|
202
|
+
const validItems = yield* validateItems(items)
|
|
203
|
+
|
|
204
|
+
const stats = calculateDetailedStats(validItems)
|
|
205
|
+
return {
|
|
206
|
+
...list.serialize(),
|
|
207
|
+
owner: owner.serialize(),
|
|
208
|
+
items: validItems.map((i) => i.serialize()),
|
|
209
|
+
stats,
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// genAdapter version
|
|
215
|
+
function processWithValidationsGenAdapter(
|
|
216
|
+
list: GroceryListEntity,
|
|
217
|
+
owner: UserEntity,
|
|
218
|
+
items: ItemEntity[],
|
|
219
|
+
) {
|
|
220
|
+
return Result.genAdapter(function* ($) {
|
|
221
|
+
yield* $(list.ensureIsOwner(owner))
|
|
222
|
+
yield* $(ensureListIsActive(list))
|
|
223
|
+
const validItems = yield* $(validateItems(items))
|
|
224
|
+
|
|
225
|
+
const stats = calculateDetailedStats(validItems)
|
|
226
|
+
return {
|
|
227
|
+
...list.serialize(),
|
|
228
|
+
owner: owner.serialize(),
|
|
229
|
+
items: validItems.map((i) => i.serialize()),
|
|
230
|
+
stats,
|
|
231
|
+
}
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
console.log(
|
|
236
|
+
"1. flatMap validation:",
|
|
237
|
+
processWithValidationsFlatMap(mockGroceryList, mockUser, mockItems)._tag,
|
|
238
|
+
)
|
|
239
|
+
console.log(
|
|
240
|
+
"2. gen validation:",
|
|
241
|
+
processWithValidationsGen(mockGroceryList, mockUser, mockItems)._tag,
|
|
242
|
+
)
|
|
243
|
+
console.log(
|
|
244
|
+
"3. genAdapter validation:",
|
|
245
|
+
processWithValidationsGenAdapter(mockGroceryList, mockUser, mockItems)._tag,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
// ============================================================================
|
|
249
|
+
// COMPARISON: Fetching and chaining
|
|
250
|
+
// ============================================================================
|
|
251
|
+
|
|
252
|
+
console.log("\n=== Fetching and Chaining Comparison ===\n")
|
|
253
|
+
|
|
254
|
+
// flatMap version
|
|
255
|
+
function fetchAndProcessFlatMap(userId: string) {
|
|
256
|
+
return fetchUserById(userId)
|
|
257
|
+
.flatMap((user) => mockGroceryList.ensureIsOwner(user))
|
|
258
|
+
.map((_) => mockGroceryList.serialize())
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// gen version
|
|
262
|
+
function fetchAndProcessGen(userId: string) {
|
|
263
|
+
return Result.gen(function* () {
|
|
264
|
+
const user = yield* fetchUserById(userId)
|
|
265
|
+
yield* mockGroceryList.ensureIsOwner(user)
|
|
266
|
+
return mockGroceryList.serialize()
|
|
267
|
+
})
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// genAdapter version
|
|
271
|
+
function fetchAndProcessGenAdapter(userId: string) {
|
|
272
|
+
return Result.genAdapter(function* ($) {
|
|
273
|
+
const user = yield* $(fetchUserById(userId))
|
|
274
|
+
yield* $(mockGroceryList.ensureIsOwner(user))
|
|
275
|
+
return mockGroceryList.serialize()
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
console.log("1. flatMap fetch:", fetchAndProcessFlatMap("user-123")._tag)
|
|
280
|
+
console.log("2. gen fetch:", fetchAndProcessGen("user-123")._tag)
|
|
281
|
+
console.log("3. genAdapter fetch:", fetchAndProcessGenAdapter("user-123")._tag)
|
|
282
|
+
|
|
283
|
+
// ============================================================================
|
|
284
|
+
// READABILITY COMPARISON
|
|
285
|
+
// ============================================================================
|
|
286
|
+
|
|
287
|
+
console.log("\n=== Readability Comparison ===\n")
|
|
288
|
+
|
|
289
|
+
console.log("flatMap chain:")
|
|
290
|
+
console.log(" - Nested structure")
|
|
291
|
+
console.log(" - Harder to read with many steps")
|
|
292
|
+
console.log(" - Explicit threading of values")
|
|
293
|
+
|
|
294
|
+
console.log("\ngen:")
|
|
295
|
+
console.log(" - Linear, imperative style")
|
|
296
|
+
console.log(" - Easy to read")
|
|
297
|
+
console.log(" - Automatic value threading")
|
|
298
|
+
|
|
299
|
+
console.log("\ngenAdapter:")
|
|
300
|
+
console.log(" - Same readability as gen")
|
|
301
|
+
console.log(" - Better type inference for complex error types")
|
|
302
|
+
console.log(" - Adapter ($) makes yields explicit")
|
|
303
|
+
|
|
304
|
+
console.log("\n=== All sync workflow examples completed ===")
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async Workflow - Process Grocery List Details with Async Operations
|
|
3
|
+
*
|
|
4
|
+
* This example shows different styles of async workflows:
|
|
5
|
+
* 1. Result.asyncGen (simplified, no adapter)
|
|
6
|
+
* 2. Result.asyncGenAdapter (with adapter for better type inference)
|
|
7
|
+
* 3. Using Result<Promise<T>, E> with auto-await
|
|
8
|
+
* 4. Complex multi-step async validation
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
12
|
+
import {
|
|
13
|
+
calculateDetailedStats,
|
|
14
|
+
calculateDetailedStatsAsync,
|
|
15
|
+
ensureListIsActive,
|
|
16
|
+
fetchItemsForListAsync,
|
|
17
|
+
fetchListWithOwnerAsync,
|
|
18
|
+
fetchUserByIdAsync,
|
|
19
|
+
filterActiveItems,
|
|
20
|
+
type GroceryListDetails,
|
|
21
|
+
GroceryListEntity,
|
|
22
|
+
type ItemEntity,
|
|
23
|
+
mockGroceryList,
|
|
24
|
+
mockItems,
|
|
25
|
+
serializeItemsAsync,
|
|
26
|
+
validateItems,
|
|
27
|
+
validateUserPermissionsAsync,
|
|
28
|
+
} from "./shared-domain"
|
|
29
|
+
|
|
30
|
+
console.log("=== Async Workflow: Process Grocery List Details ===\n")
|
|
31
|
+
|
|
32
|
+
// ============================================================================
|
|
33
|
+
// STYLE 1: Result.asyncGen (simplified)
|
|
34
|
+
// ============================================================================
|
|
35
|
+
|
|
36
|
+
async function processListDetailsAsync(
|
|
37
|
+
listId: string,
|
|
38
|
+
userId: string,
|
|
39
|
+
): Promise<GroceryListDetails> {
|
|
40
|
+
const result = await Result.asyncGen(async function* () {
|
|
41
|
+
// Fetch list with owner
|
|
42
|
+
const { list, owner } = yield* await fetchListWithOwnerAsync(listId, userId)
|
|
43
|
+
|
|
44
|
+
// Ensure ownership
|
|
45
|
+
yield* list.ensureIsOwner(owner)
|
|
46
|
+
|
|
47
|
+
// Validate list is active
|
|
48
|
+
yield* ensureListIsActive(list)
|
|
49
|
+
|
|
50
|
+
// Fetch items
|
|
51
|
+
const items = yield* await fetchItemsForListAsync(listId)
|
|
52
|
+
|
|
53
|
+
// Validate items
|
|
54
|
+
const validItems = yield* validateItems(items)
|
|
55
|
+
|
|
56
|
+
// Serialize
|
|
57
|
+
const listEncoded = list.serialize()
|
|
58
|
+
const ownerEncoded = owner.serialize()
|
|
59
|
+
const itemsEncoded = validItems.map((item) => item.serialize())
|
|
60
|
+
|
|
61
|
+
// Calculate stats
|
|
62
|
+
const stats = calculateDetailedStats(validItems)
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
id: listEncoded.id,
|
|
66
|
+
name: listEncoded.name,
|
|
67
|
+
description: listEncoded.description,
|
|
68
|
+
active: listEncoded.active,
|
|
69
|
+
owner: ownerEncoded,
|
|
70
|
+
items: itemsEncoded,
|
|
71
|
+
stats,
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
return result.unwrap()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Test asyncGen
|
|
79
|
+
console.log("1. Result.asyncGen:")
|
|
80
|
+
const asyncGenResult = await processListDetailsAsync("list-456", "user-123")
|
|
81
|
+
console.log(" Owner:", asyncGenResult.owner.name)
|
|
82
|
+
console.log(" Items:", asyncGenResult.items.length)
|
|
83
|
+
console.log(" Stats:", asyncGenResult.stats)
|
|
84
|
+
|
|
85
|
+
// ============================================================================
|
|
86
|
+
// STYLE 2: Result.asyncGenAdapter (with adapter)
|
|
87
|
+
// ============================================================================
|
|
88
|
+
|
|
89
|
+
async function processListDetailsAsyncAdapter(
|
|
90
|
+
listId: string,
|
|
91
|
+
userId: string,
|
|
92
|
+
): Promise<GroceryListDetails> {
|
|
93
|
+
const result = await Result.asyncGenAdapter(async function* ($) {
|
|
94
|
+
// Fetch list with owner
|
|
95
|
+
const { list, owner } = yield* $(
|
|
96
|
+
await fetchListWithOwnerAsync(listId, userId),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
// Ensure ownership
|
|
100
|
+
yield* $(list.ensureIsOwner(owner))
|
|
101
|
+
|
|
102
|
+
// Async permission validation
|
|
103
|
+
yield* $(await validateUserPermissionsAsync(owner, list))
|
|
104
|
+
|
|
105
|
+
// Fetch items
|
|
106
|
+
const items = yield* $(await fetchItemsForListAsync(listId))
|
|
107
|
+
|
|
108
|
+
// Validate items
|
|
109
|
+
const validItems = yield* $(validateItems(items))
|
|
110
|
+
|
|
111
|
+
// Serialize
|
|
112
|
+
const listEncoded = list.serialize()
|
|
113
|
+
const ownerEncoded = owner.serialize()
|
|
114
|
+
const itemsEncoded = validItems.map((item) => item.serialize())
|
|
115
|
+
|
|
116
|
+
// Calculate stats
|
|
117
|
+
const stats = calculateDetailedStats(validItems)
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
id: listEncoded.id,
|
|
121
|
+
name: listEncoded.name,
|
|
122
|
+
description: listEncoded.description,
|
|
123
|
+
active: listEncoded.active,
|
|
124
|
+
owner: ownerEncoded,
|
|
125
|
+
items: itemsEncoded,
|
|
126
|
+
stats,
|
|
127
|
+
}
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
return result.unwrap()
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Test asyncGenAdapter
|
|
134
|
+
console.log("\n2. Result.asyncGenAdapter:")
|
|
135
|
+
const asyncAdapterResult = await processListDetailsAsyncAdapter(
|
|
136
|
+
"list-456",
|
|
137
|
+
"user-123",
|
|
138
|
+
)
|
|
139
|
+
console.log(" Owner:", asyncAdapterResult.owner.name)
|
|
140
|
+
console.log(" Items:", asyncAdapterResult.items.length)
|
|
141
|
+
console.log(" Stats:", asyncAdapterResult.stats)
|
|
142
|
+
|
|
143
|
+
// ============================================================================
|
|
144
|
+
// STYLE 3: Using async operations directly (no map)
|
|
145
|
+
// ============================================================================
|
|
146
|
+
|
|
147
|
+
async function processListWithAsyncMappers(
|
|
148
|
+
list: GroceryListEntity,
|
|
149
|
+
items: ItemEntity[],
|
|
150
|
+
): Promise<GroceryListDetails> {
|
|
151
|
+
const result = await Result.asyncGen(async function* () {
|
|
152
|
+
const itemsValue = yield* Result.Ok(items)
|
|
153
|
+
// Do async operations outside of map
|
|
154
|
+
const itemsSerialized = await serializeItemsAsync(itemsValue)
|
|
155
|
+
|
|
156
|
+
// Same for stats calculation
|
|
157
|
+
const stats = await calculateDetailedStatsAsync(itemsValue)
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
id: list.id,
|
|
161
|
+
name: list.name,
|
|
162
|
+
description: list.description,
|
|
163
|
+
active: list.active,
|
|
164
|
+
owner: { id: "user-123", name: "Alice", email: "alice@example.com" },
|
|
165
|
+
items: itemsSerialized,
|
|
166
|
+
stats,
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
return result.unwrap()
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Test auto-await
|
|
174
|
+
console.log("\n3. Direct async operations:")
|
|
175
|
+
const autoAwaitResult = await processListWithAsyncMappers(
|
|
176
|
+
new GroceryListEntity(
|
|
177
|
+
"list-456",
|
|
178
|
+
"Weekly Shopping",
|
|
179
|
+
"desc",
|
|
180
|
+
true,
|
|
181
|
+
"user-123",
|
|
182
|
+
),
|
|
183
|
+
mockItems,
|
|
184
|
+
)
|
|
185
|
+
console.log(" Items:", autoAwaitResult.items.length)
|
|
186
|
+
console.log(" Stats:", autoAwaitResult.stats)
|
|
187
|
+
|
|
188
|
+
// ============================================================================
|
|
189
|
+
// STYLE 4: Complex multi-step async validation
|
|
190
|
+
// ============================================================================
|
|
191
|
+
|
|
192
|
+
async function processListWithFullValidationAsync(
|
|
193
|
+
listId: string,
|
|
194
|
+
userId: string,
|
|
195
|
+
) {
|
|
196
|
+
return Result.asyncGenAdapter(async function* ($) {
|
|
197
|
+
// Step 1: Fetch list and owner
|
|
198
|
+
const { list, owner } = yield* $(
|
|
199
|
+
await fetchListWithOwnerAsync(listId, userId),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
// Step 2: Ensure ownership
|
|
203
|
+
yield* $(list.ensureIsOwner(owner))
|
|
204
|
+
|
|
205
|
+
// Step 3: Async permission validation
|
|
206
|
+
yield* $(await validateUserPermissionsAsync(owner, list))
|
|
207
|
+
|
|
208
|
+
// Step 4: Validate list is active
|
|
209
|
+
yield* $(ensureListIsActive(list))
|
|
210
|
+
|
|
211
|
+
// Step 5: Fetch items
|
|
212
|
+
const items = yield* $(await fetchItemsForListAsync(listId))
|
|
213
|
+
|
|
214
|
+
// Step 6: Validate items
|
|
215
|
+
const validItems = yield* $(validateItems(items))
|
|
216
|
+
|
|
217
|
+
// Step 7: Filter active items
|
|
218
|
+
const activeItems = yield* $(filterActiveItems(validItems))
|
|
219
|
+
|
|
220
|
+
// Step 8: Async serialization
|
|
221
|
+
const itemsSerialized = await serializeItemsAsync(activeItems)
|
|
222
|
+
|
|
223
|
+
// Step 9: Async stats calculation
|
|
224
|
+
const stats = await calculateDetailedStatsAsync(activeItems)
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
id: list.id,
|
|
228
|
+
name: list.name,
|
|
229
|
+
description: list.description,
|
|
230
|
+
active: list.active,
|
|
231
|
+
owner: owner.serialize(),
|
|
232
|
+
items: itemsSerialized,
|
|
233
|
+
stats,
|
|
234
|
+
activeItemCount: activeItems.length,
|
|
235
|
+
}
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
console.log("\n4. Complex async validation:")
|
|
240
|
+
const complexResult = await processListWithFullValidationAsync(
|
|
241
|
+
"list-456",
|
|
242
|
+
"user-123",
|
|
243
|
+
)
|
|
244
|
+
console.log(" Result:", complexResult._tag)
|
|
245
|
+
if (complexResult.isOk()) {
|
|
246
|
+
const details = complexResult.unwrap()
|
|
247
|
+
console.log(" Owner:", details.owner.name)
|
|
248
|
+
console.log(" Active items:", details.activeItemCount)
|
|
249
|
+
console.log(" Stats:", details.stats)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ============================================================================
|
|
253
|
+
// ERROR HANDLING COMPARISON
|
|
254
|
+
// ============================================================================
|
|
255
|
+
|
|
256
|
+
console.log("\n=== Error Handling Comparison ===\n")
|
|
257
|
+
|
|
258
|
+
// Test with invalid user
|
|
259
|
+
const invalidUserResult = await Result.asyncGen(async function* () {
|
|
260
|
+
const { list, owner } = yield* await fetchListWithOwnerAsync(
|
|
261
|
+
"list-456",
|
|
262
|
+
"invalid",
|
|
263
|
+
)
|
|
264
|
+
yield* list.ensureIsOwner(owner)
|
|
265
|
+
return "success"
|
|
266
|
+
})
|
|
267
|
+
console.log("1. Invalid user (asyncGen):", invalidUserResult.unwrapErr()._tag)
|
|
268
|
+
|
|
269
|
+
// Test with invalid items
|
|
270
|
+
const invalidItemsResult = await Result.asyncGenAdapter(async function* ($) {
|
|
271
|
+
const { list, owner } = yield* $(
|
|
272
|
+
await fetchListWithOwnerAsync("list-456", "user-123"),
|
|
273
|
+
)
|
|
274
|
+
yield* $(list.ensureIsOwner(owner))
|
|
275
|
+
|
|
276
|
+
// Create empty items array for testing
|
|
277
|
+
const emptyItems: ItemEntity[] = []
|
|
278
|
+
yield* $(validateItems(emptyItems))
|
|
279
|
+
|
|
280
|
+
return "success"
|
|
281
|
+
})
|
|
282
|
+
console.log(
|
|
283
|
+
"2. Invalid items (asyncGenAdapter):",
|
|
284
|
+
invalidItemsResult.unwrapErr()._tag,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
// ============================================================================
|
|
288
|
+
// PERFORMANCE: Parallel-like pattern (but sequential)
|
|
289
|
+
// ============================================================================
|
|
290
|
+
|
|
291
|
+
async function fetchAllDataSequential(userId: string) {
|
|
292
|
+
const r = await Result.asyncGen(async function* () {
|
|
293
|
+
// All fetches happen sequentially but cleanly
|
|
294
|
+
const user = yield* await fetchUserByIdAsync(userId)
|
|
295
|
+
const items = yield* await fetchItemsForListAsync("list-456")
|
|
296
|
+
|
|
297
|
+
yield* await validateUserPermissionsAsync(user, mockGroceryList)
|
|
298
|
+
|
|
299
|
+
return { user, items, hasPermission: true }
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
return r
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
console.log("\n5. Sequential fetches:")
|
|
306
|
+
const sequentialResult = await fetchAllDataSequential("user-123")
|
|
307
|
+
console.log(" Result:", sequentialResult._tag)
|
|
308
|
+
|
|
309
|
+
// ===========================================================================
|
|
310
|
+
// USING DIRECT ASYNC OPERATIONS
|
|
311
|
+
// ============================================================================
|
|
312
|
+
|
|
313
|
+
async function processWithDirectAsync(items: ItemEntity[]) {
|
|
314
|
+
return Result.asyncGen(async function* () {
|
|
315
|
+
const itemsValue = yield* Result.Ok(items)
|
|
316
|
+
// Do async operations directly
|
|
317
|
+
const itemsSerialized = await serializeItemsAsync(itemsValue)
|
|
318
|
+
const stats = await calculateDetailedStatsAsync(itemsValue)
|
|
319
|
+
|
|
320
|
+
return { items: itemsSerialized, stats }
|
|
321
|
+
})
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
console.log("\n6. Direct async operations:")
|
|
325
|
+
const toPromiseResult = await processWithDirectAsync(mockItems)
|
|
326
|
+
|
|
327
|
+
if (toPromiseResult.isErr()) {
|
|
328
|
+
console.log(" Error:", toPromiseResult.unwrapErr())
|
|
329
|
+
} else {
|
|
330
|
+
const data = toPromiseResult.unwrap()
|
|
331
|
+
console.log(" Items:", data.items.length)
|
|
332
|
+
console.log(" Stats:", data.stats)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ============================================================================
|
|
336
|
+
// READABILITY COMPARISON
|
|
337
|
+
// ============================================================================
|
|
338
|
+
|
|
339
|
+
console.log("\n=== Readability Comparison ===\n")
|
|
340
|
+
|
|
341
|
+
console.log("asyncGen:")
|
|
342
|
+
console.log(" - yield* await Promise<Result<T,E>>")
|
|
343
|
+
console.log(" - Clean, linear async code")
|
|
344
|
+
console.log(" - Do async operations outside Result wrappers")
|
|
345
|
+
|
|
346
|
+
console.log("\nasyncGenAdapter:")
|
|
347
|
+
console.log(" - yield* $(await Promise<Result<T,E>>)")
|
|
348
|
+
console.log(" - Better type inference")
|
|
349
|
+
console.log(" - Explicit adapter makes yields clear")
|
|
350
|
+
|
|
351
|
+
console.log("\nBoth support:")
|
|
352
|
+
console.log(" - Mixed sync/async operations")
|
|
353
|
+
console.log(" - Automatic error short-circuiting")
|
|
354
|
+
console.log(" - Direct async functions (no map(async fn))")
|
|
355
|
+
|
|
356
|
+
console.log("\n=== All async workflow examples completed ===")
|