@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.
Files changed (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +237 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Simple Sync Workflow - Checkout Summary
3
+ *
4
+ * This example shows different styles of implementing the same workflow:
5
+ * 1. flatMap chain style
6
+ * 2. Option.gen style (simplified)
7
+ * 3. Option.genAdapter style (with adapter for better type inference)
8
+ *
9
+ * Workflow steps:
10
+ * - Fetch user
11
+ * - Ensure user is active
12
+ * - Fetch cart
13
+ * - Validate cart ownership
14
+ * - Validate cart is not empty
15
+ * - Fetch products for cart items
16
+ * - Validate stock availability
17
+ * - Calculate checkout summary
18
+ */
19
+
20
+ import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
21
+ import {
22
+ type CheckoutSummary,
23
+ calculateCheckoutSummary,
24
+ findCartById,
25
+ findProductById,
26
+ findUserById,
27
+ getProductsForCart,
28
+ validateCartNotEmpty,
29
+ validateStockAvailability,
30
+ } from "./shared-domain"
31
+
32
+ console.log("=== Simple Sync Workflow: Checkout Summary ===\n")
33
+
34
+ // ============================================================================
35
+ // STYLE 1: flatMap chain style
36
+ // ============================================================================
37
+
38
+ function processCheckoutUsingFlatMap(
39
+ userId: string,
40
+ cartId: string,
41
+ ): Option<CheckoutSummary> {
42
+ return findUserById(userId)
43
+ .flatMap((user) => user.ensureActive())
44
+ .flatMap((_user) => findCartById(cartId))
45
+ .flatMap((cart) =>
46
+ findUserById(userId).flatMap((user) => cart.ensureOwner(user)),
47
+ )
48
+ .flatMap((cart) => validateCartNotEmpty(cart))
49
+ .flatMap((cart) => getProductsForCart(cart))
50
+ .flatMap((products) =>
51
+ findCartById(cartId).flatMap((cart) =>
52
+ validateStockAvailability(products, cart.items),
53
+ ),
54
+ )
55
+ .flatMap((products) =>
56
+ findCartById(cartId).flatMap((cart) =>
57
+ findUserById(userId).map((user) =>
58
+ calculateCheckoutSummary(user, cart, products),
59
+ ),
60
+ ),
61
+ )
62
+ }
63
+
64
+ // Test flatMap style
65
+ console.log("1. flatMap chain style:")
66
+ const flatMapResult = processCheckoutUsingFlatMap("user-123", "cart-456")
67
+ if (flatMapResult.isSome()) {
68
+ const summary = flatMapResult.unwrap()
69
+ console.log(" User:", summary.user.name)
70
+ console.log(" Items:", summary.itemCount)
71
+ console.log(" Total:", summary.total)
72
+ } else {
73
+ console.log(" No checkout summary available")
74
+ }
75
+
76
+ // ============================================================================
77
+ // STYLE 2: Option.gen style (simplified, no adapter)
78
+ // ============================================================================
79
+
80
+ function processCheckoutUsingGen(
81
+ userId: string,
82
+ cartId: string,
83
+ ): Option<CheckoutSummary> {
84
+ return Option.gen(function* () {
85
+ // Step 1: Fetch and validate user
86
+ const user = yield* findUserById(userId)
87
+ yield* user.ensureActive()
88
+
89
+ // Step 2: Fetch and validate cart
90
+ const cart = yield* findCartById(cartId)
91
+ yield* cart.ensureOwner(user)
92
+
93
+ // Step 3: Validate cart has items
94
+ yield* validateCartNotEmpty(cart)
95
+
96
+ // Step 4: Fetch products for cart items
97
+ const products = yield* getProductsForCart(cart)
98
+
99
+ // Step 5: Validate stock availability
100
+ yield* validateStockAvailability(products, cart.items)
101
+
102
+ // Step 6: Calculate and return summary
103
+ return calculateCheckoutSummary(user, cart, products)
104
+ })
105
+ }
106
+
107
+ // Test gen style
108
+ console.log("\n2. Option.gen style:")
109
+ const genResult = processCheckoutUsingGen("user-123", "cart-456")
110
+ if (genResult.isSome()) {
111
+ const summary = genResult.unwrap()
112
+ console.log(" User:", summary.user.name)
113
+ console.log(" Items:", summary.itemCount)
114
+ console.log(" Total:", summary.total)
115
+ } else {
116
+ console.log(" No checkout summary available")
117
+ }
118
+
119
+ // ============================================================================
120
+ // STYLE 3: Option.genAdapter style (with adapter)
121
+ // ============================================================================
122
+
123
+ function processCheckoutUsingGenAdapter(
124
+ userId: string,
125
+ cartId: string,
126
+ ): Option<CheckoutSummary> {
127
+ return Option.genAdapter(function* ($) {
128
+ // Step 1: Fetch and validate user
129
+ const user = yield* $(findUserById(userId))
130
+ yield* $(user.ensureActive())
131
+
132
+ // Step 2: Fetch and validate cart
133
+ const cart = yield* $(findCartById(cartId))
134
+ yield* $(cart.ensureOwner(user))
135
+
136
+ // Step 3: Validate cart has items
137
+ yield* $(validateCartNotEmpty(cart))
138
+
139
+ // Step 4: Fetch products for cart items
140
+ const products = yield* $(getProductsForCart(cart))
141
+
142
+ // Step 5: Validate stock availability
143
+ yield* $(validateStockAvailability(products, cart.items))
144
+
145
+ // Step 6: Calculate and return summary
146
+ return calculateCheckoutSummary(user, cart, products)
147
+ })
148
+ }
149
+
150
+ // Test genAdapter style
151
+ console.log("\n3. Option.genAdapter style:")
152
+ const genAdapterResult = processCheckoutUsingGenAdapter("user-123", "cart-456")
153
+ if (genAdapterResult.isSome()) {
154
+ const summary = genAdapterResult.unwrap()
155
+ console.log(" User:", summary.user.name)
156
+ console.log(" Items:", summary.itemCount)
157
+ console.log(" Total:", summary.total)
158
+ } else {
159
+ console.log(" No checkout summary available")
160
+ }
161
+
162
+ // ============================================================================
163
+ // COMPARISON: Multi-step validation
164
+ // ============================================================================
165
+
166
+ console.log("\n=== Multi-step Validation Comparison ===\n")
167
+
168
+ // flatMap version
169
+ function validateWithFlatMap(userId: string, cartId: string) {
170
+ return findUserById(userId)
171
+ .flatMap((user) => user.ensureActive())
172
+ .flatZip((_user) => findCartById(cartId))
173
+ .flatMap(([user, cart]) => cart.ensureOwner(user))
174
+ .flatMap((cart) => validateCartNotEmpty(cart))
175
+ }
176
+
177
+ // gen version
178
+ function validateWithGen(userId: string, cartId: string) {
179
+ return Option.gen(function* () {
180
+ const user = yield* findUserById(userId)
181
+ yield* user.ensureActive()
182
+
183
+ const cart = yield* findCartById(cartId)
184
+ yield* cart.ensureOwner(user)
185
+
186
+ yield* validateCartNotEmpty(cart)
187
+
188
+ return { user, cart }
189
+ })
190
+ }
191
+
192
+ // genAdapter version
193
+ function validateWithGenAdapter(userId: string, cartId: string) {
194
+ return Option.genAdapter(function* ($) {
195
+ const user = yield* $(findUserById(userId))
196
+ yield* $(user.ensureActive())
197
+
198
+ const cart = yield* $(findCartById(cartId))
199
+ yield* $(cart.ensureOwner(user))
200
+
201
+ yield* $(validateCartNotEmpty(cart))
202
+
203
+ return { user, cart }
204
+ })
205
+ }
206
+
207
+ console.log(
208
+ "1. flatMap validation:",
209
+ validateWithFlatMap("user-123", "cart-456")._tag,
210
+ )
211
+ console.log("2. gen validation:", validateWithGen("user-123", "cart-456")._tag)
212
+ console.log(
213
+ "3. genAdapter validation:",
214
+ validateWithGenAdapter("user-123", "cart-456")._tag,
215
+ )
216
+
217
+ // ============================================================================
218
+ // COMPARISON: Failure scenarios
219
+ // ============================================================================
220
+
221
+ console.log("\n=== Failure Scenarios ===\n")
222
+
223
+ // Inactive user
224
+ console.log("1. Inactive user:")
225
+ console.log(
226
+ " flatMap:",
227
+ processCheckoutUsingFlatMap("user-999", "cart-456")._tag,
228
+ ) // "None"
229
+ console.log(" gen:", processCheckoutUsingGen("user-999", "cart-456")._tag) // "None"
230
+ console.log(
231
+ " genAdapter:",
232
+ processCheckoutUsingGenAdapter("user-999", "cart-456")._tag,
233
+ ) // "None"
234
+
235
+ // Empty cart
236
+ console.log("\n2. Empty cart:")
237
+ console.log(
238
+ " flatMap:",
239
+ processCheckoutUsingFlatMap("user-123", "cart-789")._tag,
240
+ ) // "None"
241
+ console.log(" gen:", processCheckoutUsingGen("user-123", "cart-789")._tag) // "None"
242
+ console.log(
243
+ " genAdapter:",
244
+ processCheckoutUsingGenAdapter("user-123", "cart-789")._tag,
245
+ ) // "None"
246
+
247
+ // Non-existent cart
248
+ console.log("\n3. Non-existent cart:")
249
+ console.log(
250
+ " flatMap:",
251
+ processCheckoutUsingFlatMap("user-123", "cart-invalid")._tag,
252
+ ) // "None"
253
+ console.log(" gen:", processCheckoutUsingGen("user-123", "cart-invalid")._tag) // "None"
254
+ console.log(
255
+ " genAdapter:",
256
+ processCheckoutUsingGenAdapter("user-123", "cart-invalid")._tag,
257
+ ) // "None"
258
+
259
+ // ============================================================================
260
+ // COMPARISON: Individual product lookup with validation
261
+ // ============================================================================
262
+
263
+ console.log("\n=== Product Lookup with Validation ===\n")
264
+
265
+ const findAndValidateProduct = (productId: string, quantity: number) => {
266
+ return findProductById(productId)
267
+ .flatMap((product) => product.ensureInStock())
268
+ .flatMap((product) => product.ensureQuantityAvailable(quantity))
269
+ }
270
+
271
+ console.log(
272
+ "1. Valid product (prod-1, qty 1):",
273
+ findAndValidateProduct("prod-1", 1)._tag,
274
+ ) // "Some"
275
+ console.log(
276
+ "2. Out of stock (prod-3, qty 1):",
277
+ findAndValidateProduct("prod-3", 1)._tag,
278
+ ) // "None"
279
+ console.log(
280
+ "3. Insufficient stock (prod-1, qty 100):",
281
+ findAndValidateProduct("prod-1", 100)._tag,
282
+ ) // "None"
283
+
284
+ // Using gen for the same
285
+ const findAndValidateProductGen = (productId: string, quantity: number) => {
286
+ return Option.gen(function* () {
287
+ const product = yield* findProductById(productId)
288
+ yield* product.ensureInStock()
289
+ yield* product.ensureQuantityAvailable(quantity)
290
+ return product
291
+ })
292
+ }
293
+
294
+ console.log(
295
+ "\n4. Using gen (prod-1, qty 1):",
296
+ findAndValidateProductGen("prod-1", 1)._tag,
297
+ ) // "Some"
298
+
299
+ // ============================================================================
300
+ // READABILITY COMPARISON
301
+ // ============================================================================
302
+
303
+ console.log("\n=== Readability Comparison ===\n")
304
+
305
+ console.log("flatMap chain:")
306
+ console.log(" - Nested structure with callbacks")
307
+ console.log(" - Harder to read with many steps")
308
+ console.log(" - Need to pass values through explicitly")
309
+
310
+ console.log("\ngen:")
311
+ console.log(" - Linear, imperative style")
312
+ console.log(" - Easy to read and follow")
313
+ console.log(" - Automatic value threading")
314
+ console.log(" - Clear step-by-step flow")
315
+
316
+ console.log("\ngenAdapter:")
317
+ console.log(" - Same readability as gen")
318
+ console.log(" - Adapter ($) makes Option operations explicit")
319
+ console.log(" - Better type inference for complex cases")
320
+
321
+ console.log("\n=== All sync workflow examples completed ===")
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Async Workflow - Checkout Summary with Async Operations
3
+ *
4
+ * This example shows different styles of async workflows:
5
+ * 1. Option.asyncGen (simplified, no adapter)
6
+ * 2. Option.asyncGenAdapter (with adapter for better type inference)
7
+ * 3. Using Option<Promise<T>> with auto-await
8
+ * 4. Complex multi-step async validation
9
+ *
10
+ * Workflow steps:
11
+ * - Fetch user (async)
12
+ * - Ensure user is active
13
+ * - Fetch cart (async)
14
+ * - Validate cart ownership
15
+ * - Validate cart is not empty (async)
16
+ * - Fetch products for cart items (async)
17
+ * - Validate stock availability (async)
18
+ * - Calculate checkout summary (async)
19
+ */
20
+
21
+ import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
22
+ import {
23
+ type CartEntity,
24
+ type CheckoutSummary,
25
+ calculateCheckoutSummaryAsync,
26
+ findCartByIdAsync,
27
+ findUserByIdAsync,
28
+ type ProductEntity,
29
+ validateCartNotEmptyAsync,
30
+ validateStockAvailabilityAsync,
31
+ } from "./shared-domain"
32
+
33
+ // Helper to get products for cart (not in shared-domain, defined here for async example)
34
+ async function getProductsForCartAsync(
35
+ cart: CartEntity,
36
+ ): Promise<Option<ProductEntity[]>> {
37
+ await new Promise((resolve) => setTimeout(resolve, 15))
38
+
39
+ const { findProductById } = await import("./shared-domain.js")
40
+
41
+ const products: ProductEntity[] = []
42
+
43
+ for (const item of cart.items) {
44
+ const product = findProductById(item.productId)
45
+ if (product.isNone()) {
46
+ return Option.None
47
+ }
48
+ products.push(product.unwrap())
49
+ }
50
+
51
+ return products.length > 0 ? Option.Some(products) : Option.None
52
+ }
53
+
54
+ console.log("=== Async Workflow: Checkout Summary ===\n")
55
+
56
+ // ============================================================================
57
+ // STYLE 1: Option.asyncGen (simplified)
58
+ // ============================================================================
59
+
60
+ async function processCheckoutAsync(
61
+ userId: string,
62
+ cartId: string,
63
+ ): Promise<Option<CheckoutSummary>> {
64
+ return await Option.asyncGen(async function* () {
65
+ // Step 1: Fetch and validate user
66
+ const user = yield* await findUserByIdAsync(userId)
67
+ yield* user.ensureActive()
68
+
69
+ // Step 2: Fetch and validate cart
70
+ const cart = yield* await findCartByIdAsync(cartId)
71
+ yield* cart.ensureOwner(user)
72
+
73
+ // Step 3: Validate cart has items
74
+ yield* await validateCartNotEmptyAsync(cart)
75
+
76
+ // Step 4: Fetch products for cart items
77
+ const products = yield* await getProductsForCartAsync(cart)
78
+
79
+ // Step 5: Validate stock availability
80
+ yield* await validateStockAvailabilityAsync(products, cart.items)
81
+
82
+ // Step 6: Calculate and return summary
83
+ return await calculateCheckoutSummaryAsync(user, cart, products)
84
+ })
85
+ }
86
+
87
+ // Test asyncGen
88
+ console.log("1. Option.asyncGen:")
89
+ const asyncGenResult = await processCheckoutAsync("user-123", "cart-456")
90
+ if (asyncGenResult.isSome()) {
91
+ const summary = asyncGenResult.unwrap()
92
+ console.log(" User:", summary.user.name)
93
+ console.log(" Items:", summary.itemCount)
94
+ console.log(" Total:", summary.total)
95
+ } else {
96
+ console.log(" No checkout summary available")
97
+ }
98
+
99
+ // ============================================================================
100
+ // STYLE 2: Option.asyncGenAdapter (with adapter)
101
+ // ============================================================================
102
+
103
+ async function processCheckoutAsyncAdapter(
104
+ userId: string,
105
+ cartId: string,
106
+ ): Promise<Option<CheckoutSummary>> {
107
+ const opt = await Option.asyncGenAdapter(async function* ($) {
108
+ // Step 1: Fetch and validate user
109
+ const user = yield* $(await findUserByIdAsync(userId))
110
+ yield* $(user.ensureActive())
111
+
112
+ // Step 2: Fetch and validate cart
113
+ const cart = yield* $(await findCartByIdAsync(cartId))
114
+ yield* $(cart.ensureOwner(user))
115
+
116
+ // Step 3: Validate cart has items
117
+ yield* $(await validateCartNotEmptyAsync(cart))
118
+
119
+ // Step 4: Fetch products for cart items
120
+ const products = yield* $(await getProductsForCartAsync(cart))
121
+
122
+ // Step 5: Validate stock availability
123
+ yield* $(await validateStockAvailabilityAsync(products, cart.items))
124
+
125
+ // Step 6: Calculate and return summary
126
+ return await calculateCheckoutSummaryAsync(user, cart, products)
127
+ })
128
+
129
+ return opt
130
+ }
131
+
132
+ // Test asyncGenAdapter
133
+ console.log("\n2. Option.asyncGenAdapter:")
134
+ const asyncAdapterResult = await processCheckoutAsyncAdapter(
135
+ "user-123",
136
+ "cart-456",
137
+ )
138
+ if (asyncAdapterResult.isSome()) {
139
+ const summary = asyncAdapterResult.unwrap()
140
+ console.log(" User:", summary.user.name)
141
+ console.log(" Items:", summary.itemCount)
142
+ console.log(" Total:", summary.total)
143
+ } else {
144
+ console.log(" No checkout summary available")
145
+ }
146
+
147
+ // ============================================================================
148
+ // STYLE 3: Using Option<Promise<T>> with auto-await
149
+ // ============================================================================
150
+
151
+ async function processWithAsyncMappers(
152
+ userId: string,
153
+ cartId: string,
154
+ ): Promise<Option<CheckoutSummary>> {
155
+ return await Option.asyncGen(async function* () {
156
+ // Option.map with async function returns Option<Promise<T>>
157
+ const userOption = await findUserByIdAsync(userId)
158
+ const user = yield* userOption // Auto-awaits inner promise
159
+
160
+ yield* user.ensureActive()
161
+
162
+ const cartOption = await findCartByIdAsync(cartId)
163
+ const cart = yield* cartOption
164
+
165
+ yield* cart.ensureOwner(user)
166
+
167
+ const products = yield* await getProductsForCartAsync(cart)
168
+ yield* await validateStockAvailabilityAsync(products, cart.items)
169
+
170
+ return await calculateCheckoutSummaryAsync(user, cart, products)
171
+ })
172
+ }
173
+
174
+ // Test auto-await
175
+ console.log("\n3. Auto-await inner promises:")
176
+ const autoAwaitResult = await processWithAsyncMappers("user-123", "cart-456")
177
+ if (autoAwaitResult.isSome()) {
178
+ const summary = autoAwaitResult.unwrap()
179
+ console.log(" Items:", summary.itemCount)
180
+ console.log(" Total:", summary.total)
181
+ }
182
+
183
+ // ============================================================================
184
+ // STYLE 4: Complex multi-step async validation
185
+ // ============================================================================
186
+
187
+ async function processWithFullValidationAsync(userId: string, cartId: string) {
188
+ return await Option.asyncGenAdapter(async function* ($) {
189
+ // Step 1: Fetch user
190
+ const user = yield* $(await findUserByIdAsync(userId))
191
+
192
+ // Step 2: Ensure user is active
193
+ yield* $(user.ensureActive())
194
+
195
+ // Step 3: Fetch cart
196
+ const cart = yield* $(await findCartByIdAsync(cartId))
197
+
198
+ // Step 4: Validate ownership
199
+ yield* $(cart.ensureOwner(user))
200
+
201
+ // Step 5: Validate cart not empty
202
+ yield* $(await validateCartNotEmptyAsync(cart))
203
+
204
+ // Step 6: Fetch products
205
+ const products = yield* $(await getProductsForCartAsync(cart))
206
+
207
+ // Step 7: Validate stock availability
208
+ yield* $(await validateStockAvailabilityAsync(products, cart.items))
209
+
210
+ // Step 8: Calculate summary
211
+ const summary = await calculateCheckoutSummaryAsync(user, cart, products)
212
+
213
+ return {
214
+ ...summary,
215
+ validatedAt: new Date().toISOString(),
216
+ }
217
+ })
218
+ }
219
+
220
+ console.log("\n4. Complex async validation:")
221
+ const complexResult = await processWithFullValidationAsync(
222
+ "user-123",
223
+ "cart-456",
224
+ )
225
+ if (complexResult.isSome()) {
226
+ const summary = complexResult.unwrap()
227
+ console.log(" Result:", summary.user.name)
228
+ console.log(" Items:", summary.itemCount)
229
+ console.log(" Total:", summary.total)
230
+ }
231
+
232
+ // ============================================================================
233
+ // ERROR HANDLING COMPARISON
234
+ // ============================================================================
235
+
236
+ console.log("\n=== Error Handling Comparison ===\n")
237
+
238
+ // Test with invalid user
239
+ const invalidUserResult = await Option.asyncGen(async function* () {
240
+ const user = yield* await findUserByIdAsync("invalid")
241
+ yield* user.ensureActive()
242
+ return "success"
243
+ })
244
+ console.log("1. Invalid user (asyncGen):", invalidUserResult._tag) // "None"
245
+
246
+ // Test with empty cart
247
+ const emptyCartResult = await Option.asyncGenAdapter(async function* ($) {
248
+ const user = yield* $(await findUserByIdAsync("user-123"))
249
+ yield* $(user.ensureActive())
250
+
251
+ const cart = yield* $(await findCartByIdAsync("cart-789"))
252
+ yield* $(cart.ensureOwner(user))
253
+
254
+ yield* $(await validateCartNotEmptyAsync(cart))
255
+
256
+ return "success"
257
+ })
258
+ console.log("2. Empty cart (asyncGenAdapter):", emptyCartResult._tag) // "None"
259
+
260
+ // ============================================================================
261
+ // PERFORMANCE: Sequential async operations
262
+ // ============================================================================
263
+
264
+ async function fetchAllDataSequential(userId: string, cartId: string) {
265
+ return await Option.asyncGen(async function* () {
266
+ // All fetches happen sequentially but cleanly
267
+ const user = yield* await findUserByIdAsync(userId)
268
+ const cart = yield* await findCartByIdAsync(cartId)
269
+
270
+ yield* cart.ensureOwner(user)
271
+
272
+ return { user, cart, hasPermission: true }
273
+ })
274
+ }
275
+
276
+ console.log("\n3. Sequential fetches:")
277
+ const sequentialResult = await fetchAllDataSequential("user-123", "cart-456")
278
+ console.log(" Result:", sequentialResult._tag)
279
+
280
+ // ============================================================================
281
+ // USING TOPROMISE FOR CONVERSION
282
+ // ============================================================================
283
+
284
+ async function processWithToPromise(userId: string, cartId: string) {
285
+ return await Option.asyncGen(async function* () {
286
+ const user = yield* await findUserByIdAsync(userId)
287
+ yield* user.ensureActive()
288
+
289
+ const cart = yield* await findCartByIdAsync(cartId)
290
+ yield* cart.ensureOwner(user)
291
+
292
+ const products = yield* await getProductsForCartAsync(cart)
293
+
294
+ return await calculateCheckoutSummaryAsync(user, cart, products)
295
+ })
296
+ }
297
+
298
+ console.log("\n4. Using toPromise:")
299
+ const toPromiseResult = await processWithToPromise("user-123", "cart-456")
300
+
301
+ if (toPromiseResult.isNone()) {
302
+ console.log(" No checkout summary")
303
+ } else {
304
+ const summary = toPromiseResult.unwrap()
305
+ console.log(" Items:", summary.itemCount)
306
+ console.log(" Total:", summary.total)
307
+ }
308
+
309
+ // ============================================================================
310
+ // MIXED SYNC AND ASYNC OPERATIONS
311
+ // ============================================================================
312
+
313
+ async function processMixedOperations(userId: string, cartId: string) {
314
+ return await Option.asyncGenAdapter(async function* ($) {
315
+ // Async: fetch user
316
+ const user = yield* $(await findUserByIdAsync(userId))
317
+
318
+ // Sync: validate active
319
+ yield* $(user.ensureActive())
320
+
321
+ // Async: fetch cart
322
+ const cart = yield* $(await findCartByIdAsync(cartId))
323
+
324
+ // Sync: validate ownership
325
+ yield* $(cart.ensureOwner(user))
326
+
327
+ // Async: validate cart not empty
328
+ yield* $(await validateCartNotEmptyAsync(cart))
329
+
330
+ // Sync: get item count
331
+ const itemCount = cart.items.length
332
+
333
+ // Async: fetch products
334
+ const products = yield* $(await getProductsForCartAsync(cart))
335
+
336
+ // Return mixed sync/async data
337
+ return {
338
+ itemCount, // sync
339
+ products, // from async
340
+ total: cart.getTotal(), // sync
341
+ }
342
+ })
343
+ }
344
+
345
+ console.log("\n5. Mixed sync/async operations:")
346
+ const mixedResult = await processMixedOperations("user-123", "cart-456")
347
+ if (mixedResult.isSome()) {
348
+ const data = mixedResult.unwrap()
349
+ console.log(" Items:", data.itemCount)
350
+ console.log(" Products:", data.products.length)
351
+ console.log(" Total:", data.total)
352
+ }
353
+
354
+ // ============================================================================
355
+ // READABILITY COMPARISON
356
+ // ============================================================================
357
+
358
+ console.log("\n=== Readability Comparison ===\n")
359
+
360
+ console.log("asyncGen:")
361
+ console.log(" - yield* await Promise<Option<T>>")
362
+ console.log(" - Auto-awaits Option<Promise<T>>")
363
+ console.log(" - Clean, linear async code")
364
+ console.log(" - Implicit adapter handling")
365
+
366
+ console.log("\nasyncGenAdapter:")
367
+ console.log(" - yield* $(await Promise<Option<T>>)")
368
+ console.log(" - Explicit adapter function ($)")
369
+ console.log(" - Better type inference")
370
+ console.log(" - Clearer Option operation boundaries")
371
+
372
+ console.log("\nBoth support:")
373
+ console.log(" - Mixed sync/async operations")
374
+ console.log(" - Automatic None short-circuiting")
375
+ console.log(" - Async mappers via Option<Promise<T>>")
376
+ console.log(" - toPromise conversion")
377
+
378
+ console.log("\n=== All async workflow examples completed ===")