@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,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ExperimentalOption Examples Index
|
|
3
|
+
*
|
|
4
|
+
* This file lists all available examples and demonstrates different
|
|
5
|
+
* patterns for working with ExperimentalOption types.
|
|
6
|
+
*
|
|
7
|
+
* NOTE: These examples are experimental-only and may change.
|
|
8
|
+
* For stable Option examples, see README.md.
|
|
9
|
+
*
|
|
10
|
+
* Run examples with:
|
|
11
|
+
* bun run examples/option-experimental/01-map.ts
|
|
12
|
+
* bun run examples/option-experimental/02-flatMap.ts
|
|
13
|
+
* etc.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
// ============================================================================
|
|
17
|
+
// BASIC OPERATIONS (files 01-04)
|
|
18
|
+
// ============================================================================
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 01-map.ts - Transform the Some value
|
|
22
|
+
*
|
|
23
|
+
* Topics covered:
|
|
24
|
+
* - Basic map usage
|
|
25
|
+
* - Map on None (mapper not called)
|
|
26
|
+
* - Chaining multiple maps
|
|
27
|
+
* - Map with object transformation
|
|
28
|
+
* - Map with async functions (returns Option<Promise<T>>)
|
|
29
|
+
* - Map with array operations
|
|
30
|
+
* - Type transformations
|
|
31
|
+
* - mapOr for default values
|
|
32
|
+
* - Async mapOr
|
|
33
|
+
*
|
|
34
|
+
* Run: bun run examples/option-experimental/01-map.ts
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 02-flatMap.ts - Chain Option-returning functions
|
|
39
|
+
*
|
|
40
|
+
* Topics covered:
|
|
41
|
+
* - Basic flatMap chains
|
|
42
|
+
* - Short-circuit on None
|
|
43
|
+
* - Chaining multiple flatMaps
|
|
44
|
+
* - Dependent lookups (user → posts)
|
|
45
|
+
* - Validation pipelines
|
|
46
|
+
* - Async flatMap
|
|
47
|
+
* - flatMap vs map comparison
|
|
48
|
+
* - Practical user lookup chain
|
|
49
|
+
* - Nested object access
|
|
50
|
+
* - Safe array element access
|
|
51
|
+
* - flatMap with Option.all
|
|
52
|
+
* - JSON parsing and validation
|
|
53
|
+
* - Configuration lookup
|
|
54
|
+
*
|
|
55
|
+
* Run: bun run examples/option-experimental/02-flatMap.ts
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 03-zip.ts - Pair original with derived value
|
|
60
|
+
*
|
|
61
|
+
* Topics covered:
|
|
62
|
+
* - Basic zip usage
|
|
63
|
+
* - Zip on None
|
|
64
|
+
* - Async zip
|
|
65
|
+
* - Validation with context
|
|
66
|
+
* - Multiple zips
|
|
67
|
+
* - Audit trail patterns
|
|
68
|
+
* - Before/after comparisons
|
|
69
|
+
* - Transformation history
|
|
70
|
+
* - Form field validation
|
|
71
|
+
* - Accumulating calculations
|
|
72
|
+
* - Async API call patterns
|
|
73
|
+
* - Value with metadata
|
|
74
|
+
* - Safe division with context
|
|
75
|
+
*
|
|
76
|
+
* Run: bun run examples/option-experimental/03-zip.ts
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 04-flatZip.ts - Pair original with Option-returning function
|
|
81
|
+
*
|
|
82
|
+
* Topics covered:
|
|
83
|
+
* - Basic flatZip usage
|
|
84
|
+
* - Short-circuit on None
|
|
85
|
+
* - Chaining flatZips
|
|
86
|
+
* - Async flatZip
|
|
87
|
+
* - User and posts pattern
|
|
88
|
+
* - Dependent lookups
|
|
89
|
+
* - Validation with context
|
|
90
|
+
* - Complex object building
|
|
91
|
+
* - flatZip vs flatMap comparison
|
|
92
|
+
* - Audit log patterns
|
|
93
|
+
* - Context preservation
|
|
94
|
+
* - Multi-step validation
|
|
95
|
+
* - Branching logic
|
|
96
|
+
*
|
|
97
|
+
* Run: bun run examples/option-experimental/04-flatZip.ts
|
|
98
|
+
*/
|
|
99
|
+
|
|
100
|
+
// ============================================================================
|
|
101
|
+
// GENERATOR-BASED SYNTAX (files 05-08)
|
|
102
|
+
// ============================================================================
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 05-gen.ts - Imperative-style sync Option composition
|
|
106
|
+
*
|
|
107
|
+
* Topics covered:
|
|
108
|
+
* - Simple gen with single/multiple yields
|
|
109
|
+
* - Short-circuit on None
|
|
110
|
+
* - Function calls in gen
|
|
111
|
+
* - Validation pipelines
|
|
112
|
+
* - gen vs flatMap readability
|
|
113
|
+
* - Complex object building
|
|
114
|
+
* - Intermediate processing
|
|
115
|
+
* - Array operations
|
|
116
|
+
* - Dependent operations
|
|
117
|
+
* - No yields case
|
|
118
|
+
* - Type information preservation
|
|
119
|
+
* - UnwrapOrElse pattern
|
|
120
|
+
* - Data transformation pipeline
|
|
121
|
+
* - Accumulator patterns
|
|
122
|
+
* - Stack overflow prevention (many yields)
|
|
123
|
+
* - Conditional logic
|
|
124
|
+
* - Safe navigation through nested objects
|
|
125
|
+
* - Option.all and Option.any in gen
|
|
126
|
+
* - Match in gen
|
|
127
|
+
* - Complex pipelines
|
|
128
|
+
*
|
|
129
|
+
* Run: bun run examples/option-experimental/05-gen.ts
|
|
130
|
+
*/
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 06-genAdapter.ts - Generator with adapter for better type inference
|
|
134
|
+
*
|
|
135
|
+
* Topics covered:
|
|
136
|
+
* - Adapter function ($) usage
|
|
137
|
+
* - Improved type inference
|
|
138
|
+
* - Method calls on objects
|
|
139
|
+
* - API composition
|
|
140
|
+
* - Conditional logic
|
|
141
|
+
* - Safe parsing utilities
|
|
142
|
+
* - Multi-step validation
|
|
143
|
+
* - Array iteration
|
|
144
|
+
* - Accumulator patterns
|
|
145
|
+
* - Transaction-like operations
|
|
146
|
+
* - gen vs genAdapter comparison
|
|
147
|
+
* - Option.all and Option.any
|
|
148
|
+
* - Nested operations
|
|
149
|
+
* - FromPredicate usage
|
|
150
|
+
*
|
|
151
|
+
* Run: bun run examples/option-experimental/06-genAdapter.ts
|
|
152
|
+
*/
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 07-asyncGen.ts - Imperative-style async Option composition
|
|
156
|
+
*
|
|
157
|
+
* Topics covered:
|
|
158
|
+
* - Simple asyncGen with sync/async Options
|
|
159
|
+
* - Multiple yields with mixed sync/async
|
|
160
|
+
* - Short-circuit on None
|
|
161
|
+
* - Async operations with delays
|
|
162
|
+
* - Fetching data patterns
|
|
163
|
+
* - Auto-awaiting Option<Promise<T>>
|
|
164
|
+
* - Async validation pipelines
|
|
165
|
+
* - Mixed sync and async yields
|
|
166
|
+
* - Dependent async lookups
|
|
167
|
+
* - Promise<Option<T>> handling
|
|
168
|
+
* - Complex async workflows
|
|
169
|
+
* - toPromise conversion
|
|
170
|
+
* - Retry-like patterns
|
|
171
|
+
* - Array processing
|
|
172
|
+
* - Conditional async operations
|
|
173
|
+
* - Batch operations
|
|
174
|
+
*
|
|
175
|
+
* Run: bun run examples/option-experimental/07-asyncGen.ts
|
|
176
|
+
*/
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 08-asyncGenAdapter.ts - Async generator with adapter
|
|
180
|
+
*
|
|
181
|
+
* Topics covered:
|
|
182
|
+
* - Adapter function ($) in async context
|
|
183
|
+
* - Promise<Option<T>> handling
|
|
184
|
+
* - Option<Promise<T>> with auto-await
|
|
185
|
+
* - Improved type inference
|
|
186
|
+
* - API composition
|
|
187
|
+
* - Complex async validation
|
|
188
|
+
* - Transaction workflows
|
|
189
|
+
* - Retry logic with fallbacks
|
|
190
|
+
* - Data processing pipelines
|
|
191
|
+
* - Array operations
|
|
192
|
+
* - Conditional logic
|
|
193
|
+
* - Batch operations
|
|
194
|
+
* - Parallel-like patterns (sequential)
|
|
195
|
+
* - toPromise usage
|
|
196
|
+
* - Complex workflows (checkout flow)
|
|
197
|
+
* - Error recovery
|
|
198
|
+
* - Nested operations
|
|
199
|
+
* - Streaming-like patterns
|
|
200
|
+
* - State management
|
|
201
|
+
*
|
|
202
|
+
* Run: bun run examples/option-experimental/08-asyncGenAdapter.ts
|
|
203
|
+
*/
|
|
204
|
+
|
|
205
|
+
// ============================================================================
|
|
206
|
+
// WORKFLOW EXAMPLES (files 09-10)
|
|
207
|
+
// ============================================================================
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 09-workflow-simple-sync.ts - Real-world sync workflow
|
|
211
|
+
*
|
|
212
|
+
* Domain: E-commerce checkout summary
|
|
213
|
+
*
|
|
214
|
+
* Comparisons shown:
|
|
215
|
+
* - flatMap chain style
|
|
216
|
+
* - Option.gen style
|
|
217
|
+
* - Option.genAdapter style
|
|
218
|
+
*
|
|
219
|
+
* Workflow steps:
|
|
220
|
+
* - Fetch user
|
|
221
|
+
* - Ensure user is active
|
|
222
|
+
* - Fetch cart
|
|
223
|
+
* - Validate cart ownership
|
|
224
|
+
* - Validate cart is not empty
|
|
225
|
+
* - Fetch products for cart items
|
|
226
|
+
* - Validate stock availability
|
|
227
|
+
* - Calculate checkout summary
|
|
228
|
+
*
|
|
229
|
+
* Also covers:
|
|
230
|
+
* - Multi-step validation comparison
|
|
231
|
+
* - Failure scenarios (inactive user, empty cart, non-existent cart)
|
|
232
|
+
* - Product lookup with validation
|
|
233
|
+
* - Readability comparison
|
|
234
|
+
*
|
|
235
|
+
* Run: bun run examples/option-experimental/09-workflow-simple-sync.ts
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* 10-workflow-async.ts - Real-world async workflow
|
|
240
|
+
*
|
|
241
|
+
* Domain: E-commerce checkout summary with async operations
|
|
242
|
+
*
|
|
243
|
+
* Styles shown:
|
|
244
|
+
* - Option.asyncGen
|
|
245
|
+
* - Option.asyncGenAdapter
|
|
246
|
+
* - Auto-awaiting Option<Promise<T>>
|
|
247
|
+
* - Complex multi-step async validation
|
|
248
|
+
*
|
|
249
|
+
* Workflow steps:
|
|
250
|
+
* - Fetch user (async)
|
|
251
|
+
* - Ensure user is active
|
|
252
|
+
* - Fetch cart (async)
|
|
253
|
+
* - Validate cart ownership
|
|
254
|
+
* - Validate cart is not empty (async)
|
|
255
|
+
* - Fetch products for cart items (async)
|
|
256
|
+
* - Validate stock availability (async)
|
|
257
|
+
* - Calculate checkout summary (async)
|
|
258
|
+
*
|
|
259
|
+
* Also covers:
|
|
260
|
+
* - Error handling comparison
|
|
261
|
+
* - Sequential async fetch patterns
|
|
262
|
+
* - toPromise conversion
|
|
263
|
+
* - Mixed sync/async operations
|
|
264
|
+
* - Readability comparison
|
|
265
|
+
*
|
|
266
|
+
* Run: bun run examples/option-experimental/10-workflow-async.ts
|
|
267
|
+
*/
|
|
268
|
+
|
|
269
|
+
// ============================================================================
|
|
270
|
+
// SHARED DOMAIN (for workflow examples)
|
|
271
|
+
// ============================================================================
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* shared-domain.ts - Domain models used in workflow examples
|
|
275
|
+
*
|
|
276
|
+
* Contains:
|
|
277
|
+
* - UserEntity, ProductEntity, CartItemEntity, CartEntity classes
|
|
278
|
+
* - CheckoutSummary interface
|
|
279
|
+
* - Mock data (users, products, carts)
|
|
280
|
+
* - Repository methods (sync and async)
|
|
281
|
+
* - Validation functions
|
|
282
|
+
*
|
|
283
|
+
* Imported by: 09-workflow-simple-sync.ts, 10-workflow-async.ts
|
|
284
|
+
*/
|
|
285
|
+
|
|
286
|
+
// ============================================================================
|
|
287
|
+
// QUICK REFERENCE
|
|
288
|
+
// ============================================================================
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* WHEN TO USE EACH METHOD:
|
|
292
|
+
*
|
|
293
|
+
* map():
|
|
294
|
+
* - Transform Some value
|
|
295
|
+
* - None bypasses mapper
|
|
296
|
+
* - Use for simple transformations
|
|
297
|
+
*
|
|
298
|
+
* mapOr():
|
|
299
|
+
* - Transform or return default value
|
|
300
|
+
* - Returns U, not Option<U>
|
|
301
|
+
* - Use for providing fallbacks
|
|
302
|
+
*
|
|
303
|
+
* flatMap():
|
|
304
|
+
* - Chain Option-returning functions
|
|
305
|
+
* - Stop on first None
|
|
306
|
+
* - Use for dependent operations
|
|
307
|
+
*
|
|
308
|
+
* zip():
|
|
309
|
+
* - Keep original value along with transformed value
|
|
310
|
+
* - Returns [original, derived] tuple
|
|
311
|
+
* - Use for audit trails, context preservation
|
|
312
|
+
*
|
|
313
|
+
* flatZip():
|
|
314
|
+
* - Like zip, but function returns Option
|
|
315
|
+
* - Stop on first None
|
|
316
|
+
* - Use for dependent operations with context
|
|
317
|
+
*
|
|
318
|
+
* gen():
|
|
319
|
+
* - Imperative-style sync code
|
|
320
|
+
* - Multiple yields with automatic threading
|
|
321
|
+
* - Short-circuits on None
|
|
322
|
+
* - Use for complex multi-step operations
|
|
323
|
+
*
|
|
324
|
+
* genAdapter():
|
|
325
|
+
* - Same as gen, with adapter function ($)
|
|
326
|
+
* - Better type inference for complex cases
|
|
327
|
+
* - Makes Option operations explicit
|
|
328
|
+
*
|
|
329
|
+
* asyncGen():
|
|
330
|
+
* - Imperative-style async code
|
|
331
|
+
* - Handles Promise<Option<T>> and Option<Promise<T>>
|
|
332
|
+
* - Auto-awaits inner promises
|
|
333
|
+
* - Use for async workflows
|
|
334
|
+
*
|
|
335
|
+
* asyncGenAdapter():
|
|
336
|
+
* - Same as asyncGen, with adapter ($)
|
|
337
|
+
* - Best type inference for async workflows
|
|
338
|
+
* - Explicit adapter makes yields clear
|
|
339
|
+
*/
|
|
340
|
+
|
|
341
|
+
export {}
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared domain models for workflow examples
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
|
|
6
|
+
|
|
7
|
+
// ============================================================================
|
|
8
|
+
// DOMAIN MODELS
|
|
9
|
+
// ============================================================================
|
|
10
|
+
|
|
11
|
+
type UserId = string
|
|
12
|
+
type ProductId = string
|
|
13
|
+
type CartId = string
|
|
14
|
+
|
|
15
|
+
// User Entity
|
|
16
|
+
export class UserEntity {
|
|
17
|
+
constructor(
|
|
18
|
+
readonly id: UserId,
|
|
19
|
+
readonly name: string,
|
|
20
|
+
readonly email: string,
|
|
21
|
+
readonly isActive: boolean,
|
|
22
|
+
) {}
|
|
23
|
+
|
|
24
|
+
serialize() {
|
|
25
|
+
return {
|
|
26
|
+
id: this.id,
|
|
27
|
+
name: this.name,
|
|
28
|
+
email: this.email,
|
|
29
|
+
isActive: this.isActive,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
ensureActive(): Option<this> {
|
|
34
|
+
return this.isActive ? Option.Some(this) : Option.None
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Product Entity
|
|
39
|
+
export class ProductEntity {
|
|
40
|
+
constructor(
|
|
41
|
+
readonly id: ProductId,
|
|
42
|
+
readonly name: string,
|
|
43
|
+
readonly price: number,
|
|
44
|
+
readonly inStock: boolean,
|
|
45
|
+
readonly stockQuantity: number,
|
|
46
|
+
) {}
|
|
47
|
+
|
|
48
|
+
serialize() {
|
|
49
|
+
return {
|
|
50
|
+
id: this.id,
|
|
51
|
+
name: this.name,
|
|
52
|
+
price: this.price,
|
|
53
|
+
inStock: this.inStock,
|
|
54
|
+
stockQuantity: this.stockQuantity,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
ensureInStock(): Option<this> {
|
|
59
|
+
return this.inStock && this.stockQuantity > 0
|
|
60
|
+
? Option.Some(this)
|
|
61
|
+
: Option.None
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
ensureQuantityAvailable(quantity: number): Option<this> {
|
|
65
|
+
return this.stockQuantity >= quantity ? Option.Some(this) : Option.None
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Cart Item Entity
|
|
70
|
+
export class CartItemEntity {
|
|
71
|
+
constructor(
|
|
72
|
+
readonly productId: ProductId,
|
|
73
|
+
readonly quantity: number,
|
|
74
|
+
readonly priceAtAdd: number,
|
|
75
|
+
) {}
|
|
76
|
+
|
|
77
|
+
withQuantity(quantity: number): CartItemEntity {
|
|
78
|
+
return new CartItemEntity(this.productId, quantity, this.priceAtAdd)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
serialize() {
|
|
82
|
+
return {
|
|
83
|
+
productId: this.productId,
|
|
84
|
+
quantity: this.quantity,
|
|
85
|
+
priceAtAdd: this.priceAtAdd,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Cart Entity
|
|
91
|
+
export class CartEntity {
|
|
92
|
+
constructor(
|
|
93
|
+
readonly id: CartId,
|
|
94
|
+
readonly userId: UserId,
|
|
95
|
+
readonly items: CartItemEntity[],
|
|
96
|
+
readonly createdAt: Date,
|
|
97
|
+
) {}
|
|
98
|
+
|
|
99
|
+
serialize() {
|
|
100
|
+
return {
|
|
101
|
+
id: this.id,
|
|
102
|
+
userId: this.userId,
|
|
103
|
+
items: this.items.map((item) => item.serialize()),
|
|
104
|
+
createdAt: this.createdAt.toISOString(),
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
ensureOwner(user: UserEntity): Option<this> {
|
|
109
|
+
return this.userId === user.id ? Option.Some(this) : Option.None
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
getTotal(): number {
|
|
113
|
+
return this.items.reduce(
|
|
114
|
+
(sum, item) => sum + item.priceAtAdd * item.quantity,
|
|
115
|
+
0,
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
isEmpty(): boolean {
|
|
120
|
+
return this.items.length === 0
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Checkout Summary
|
|
125
|
+
export interface CheckoutSummary {
|
|
126
|
+
user: ReturnType<UserEntity["serialize"]>
|
|
127
|
+
cart: ReturnType<CartEntity["serialize"]>
|
|
128
|
+
products: ReturnType<ProductEntity["serialize"]>[]
|
|
129
|
+
total: number
|
|
130
|
+
itemCount: number
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ============================================================================
|
|
134
|
+
// MOCK DATA
|
|
135
|
+
// ============================================================================
|
|
136
|
+
|
|
137
|
+
export const mockUser = new UserEntity(
|
|
138
|
+
"user-123",
|
|
139
|
+
"Alice",
|
|
140
|
+
"alice@example.com",
|
|
141
|
+
true,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
export const mockInactiveUser = new UserEntity(
|
|
145
|
+
"user-999",
|
|
146
|
+
"Bob",
|
|
147
|
+
"bob@example.com",
|
|
148
|
+
false,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
export const mockProduct1 = new ProductEntity(
|
|
152
|
+
"prod-1",
|
|
153
|
+
"Laptop",
|
|
154
|
+
999.99,
|
|
155
|
+
true,
|
|
156
|
+
10,
|
|
157
|
+
)
|
|
158
|
+
export const mockProduct2 = new ProductEntity(
|
|
159
|
+
"prod-2",
|
|
160
|
+
"Mouse",
|
|
161
|
+
29.99,
|
|
162
|
+
true,
|
|
163
|
+
50,
|
|
164
|
+
)
|
|
165
|
+
export const mockProduct3 = new ProductEntity(
|
|
166
|
+
"prod-3",
|
|
167
|
+
"Keyboard",
|
|
168
|
+
79.99,
|
|
169
|
+
false,
|
|
170
|
+
0,
|
|
171
|
+
) // Out of stock
|
|
172
|
+
|
|
173
|
+
export const mockCartItems = [
|
|
174
|
+
new CartItemEntity("prod-1", 1, 999.99),
|
|
175
|
+
new CartItemEntity("prod-2", 2, 29.99),
|
|
176
|
+
]
|
|
177
|
+
|
|
178
|
+
export const mockCart = new CartEntity(
|
|
179
|
+
"cart-456",
|
|
180
|
+
"user-123",
|
|
181
|
+
mockCartItems,
|
|
182
|
+
new Date("2024-01-15T10:00:00Z"),
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
export const mockEmptyCart = new CartEntity(
|
|
186
|
+
"cart-789",
|
|
187
|
+
"user-123",
|
|
188
|
+
[],
|
|
189
|
+
new Date("2024-01-15T10:00:00Z"),
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
// ============================================================================
|
|
193
|
+
// REPOSITORY/WORKFLOW METHODS
|
|
194
|
+
// ============================================================================
|
|
195
|
+
|
|
196
|
+
// SYNC methods returning Option
|
|
197
|
+
export function findUserById(id: UserId): Option<UserEntity> {
|
|
198
|
+
if (id === "user-123") {
|
|
199
|
+
return Option.Some(mockUser)
|
|
200
|
+
}
|
|
201
|
+
if (id === "user-999") {
|
|
202
|
+
return Option.Some(mockInactiveUser)
|
|
203
|
+
}
|
|
204
|
+
return Option.None
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function findProductById(id: ProductId): Option<ProductEntity> {
|
|
208
|
+
if (id === "prod-1") return Option.Some(mockProduct1)
|
|
209
|
+
if (id === "prod-2") return Option.Some(mockProduct2)
|
|
210
|
+
if (id === "prod-3") return Option.Some(mockProduct3)
|
|
211
|
+
return Option.None
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function findCartById(id: CartId): Option<CartEntity> {
|
|
215
|
+
if (id === "cart-456") return Option.Some(mockCart)
|
|
216
|
+
if (id === "cart-789") return Option.Some(mockEmptyCart)
|
|
217
|
+
return Option.None
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function validateCartNotEmpty(cart: CartEntity): Option<CartEntity> {
|
|
221
|
+
return !cart.isEmpty() ? Option.Some(cart) : Option.None
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function getProductsForCart(cart: CartEntity): Option<ProductEntity[]> {
|
|
225
|
+
const products: ProductEntity[] = []
|
|
226
|
+
|
|
227
|
+
for (const item of cart.items) {
|
|
228
|
+
const product = findProductById(item.productId)
|
|
229
|
+
if (product.isNone()) {
|
|
230
|
+
return Option.None
|
|
231
|
+
}
|
|
232
|
+
products.push(product.unwrap())
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return products.length > 0 ? Option.Some(products) : Option.None
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function validateStockAvailability(
|
|
239
|
+
products: ProductEntity[],
|
|
240
|
+
cartItems: CartItemEntity[],
|
|
241
|
+
): Option<ProductEntity[]> {
|
|
242
|
+
for (let i = 0; i < products.length; i++) {
|
|
243
|
+
// biome-ignore lint/style/noNonNullAssertion: example
|
|
244
|
+
const product = products[i]!
|
|
245
|
+
// biome-ignore lint/style/noNonNullAssertion: example
|
|
246
|
+
const cartItem = cartItems[i]!
|
|
247
|
+
|
|
248
|
+
const available = product
|
|
249
|
+
.ensureInStock()
|
|
250
|
+
.flatMap((p) => p.ensureQuantityAvailable(cartItem.quantity))
|
|
251
|
+
|
|
252
|
+
if (available.isNone()) {
|
|
253
|
+
return Option.None
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return Option.Some(products)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function calculateCheckoutSummary(
|
|
261
|
+
user: UserEntity,
|
|
262
|
+
cart: CartEntity,
|
|
263
|
+
products: ProductEntity[],
|
|
264
|
+
): CheckoutSummary {
|
|
265
|
+
return {
|
|
266
|
+
user: user.serialize(),
|
|
267
|
+
cart: cart.serialize(),
|
|
268
|
+
products: products.map((p) => p.serialize()),
|
|
269
|
+
total: cart.getTotal(),
|
|
270
|
+
itemCount: cart.items.length,
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ASYNC methods returning Promise<Option>
|
|
275
|
+
export async function findUserByIdAsync(
|
|
276
|
+
id: UserId,
|
|
277
|
+
): Promise<Option<UserEntity>> {
|
|
278
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
279
|
+
return findUserById(id)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export async function findProductByIdAsync(
|
|
283
|
+
id: ProductId,
|
|
284
|
+
): Promise<Option<ProductEntity>> {
|
|
285
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
286
|
+
return findProductById(id)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export async function findCartByIdAsync(
|
|
290
|
+
id: CartId,
|
|
291
|
+
): Promise<Option<CartEntity>> {
|
|
292
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
293
|
+
return findCartById(id)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export async function validateCartNotEmptyAsync(
|
|
297
|
+
cart: CartEntity,
|
|
298
|
+
): Promise<Option<CartEntity>> {
|
|
299
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
300
|
+
return validateCartNotEmpty(cart)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export async function getProductsForCartAsync(
|
|
304
|
+
cart: CartEntity,
|
|
305
|
+
): Promise<Option<ProductEntity[]>> {
|
|
306
|
+
await new Promise((resolve) => setTimeout(resolve, 15))
|
|
307
|
+
return getProductsForCart(cart)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export async function validateStockAvailabilityAsync(
|
|
311
|
+
products: ProductEntity[],
|
|
312
|
+
cartItems: CartItemEntity[],
|
|
313
|
+
): Promise<Option<ProductEntity[]>> {
|
|
314
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
315
|
+
return validateStockAvailability(products, cartItems)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function calculateCheckoutSummaryAsync(
|
|
319
|
+
user: UserEntity,
|
|
320
|
+
cart: CartEntity,
|
|
321
|
+
products: ProductEntity[],
|
|
322
|
+
): Promise<CheckoutSummary> {
|
|
323
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
324
|
+
return calculateCheckoutSummary(user, cart, products)
|
|
325
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
const ok = Result.Ok(5)
|
|
4
|
+
const err = Result.Err("Missing value")
|
|
5
|
+
|
|
6
|
+
console.log("ok isOk:", ok.isOk())
|
|
7
|
+
console.log("err isErr:", err.isErr())
|
|
8
|
+
|
|
9
|
+
const matched = ok.match({
|
|
10
|
+
Ok: (value) => `Value: ${value}`,
|
|
11
|
+
Err: () => "Error",
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
console.log("match:", matched)
|
|
15
|
+
console.log("unwrapOr:", err.unwrapOr(0))
|
|
16
|
+
console.log("safeUnwrap:", err.safeUnwrap())
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
type User = { name: string; age: number }
|
|
4
|
+
|
|
5
|
+
const doubled = Result.Ok(3).map((value) => value * 2)
|
|
6
|
+
console.log("map:", doubled.unwrap())
|
|
7
|
+
|
|
8
|
+
const validateUserData = (name: string, age: number): Result<User, Error> => {
|
|
9
|
+
if (name.trim() === "") {
|
|
10
|
+
return Result.Err(new Error("Name cannot be empty"))
|
|
11
|
+
}
|
|
12
|
+
if (age < 0 || age > 120) {
|
|
13
|
+
return Result.Err(new Error("Age must be between 0 and 120"))
|
|
14
|
+
}
|
|
15
|
+
return Result.Ok({ name, age })
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const saveUserData = async (user: User): Promise<Result<string, Error>> => {
|
|
19
|
+
await Promise.resolve(user)
|
|
20
|
+
return Result.Ok(`User ${user.name} saved successfully!`)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const processUser = async (
|
|
24
|
+
name: string,
|
|
25
|
+
age: number,
|
|
26
|
+
): Promise<Result<string, Error>> => {
|
|
27
|
+
return await validateUserData(name, age).flatMap(saveUserData).toPromise()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const result = await processUser("Alice", 30)
|
|
31
|
+
console.log("flatMap ok:", result.unwrap())
|
|
32
|
+
|
|
33
|
+
const invalid = await processUser("", 30)
|
|
34
|
+
console.log("flatMap err:", invalid.unwrapErr().message)
|