@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.
Files changed (146) hide show
  1. package/README.md +310 -96
  2. package/dist/errors.cjs +1 -0
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.cts.map +1 -1
  5. package/dist/errors.d.mts.map +1 -1
  6. package/dist/errors.mjs.map +1 -1
  7. package/dist/flow-experimental.cjs +286 -0
  8. package/dist/flow-experimental.cjs.map +1 -0
  9. package/dist/flow-experimental.d.cts +69 -0
  10. package/dist/flow-experimental.d.cts.map +1 -0
  11. package/dist/flow-experimental.d.mts +69 -0
  12. package/dist/flow-experimental.d.mts.map +1 -0
  13. package/dist/flow-experimental.mjs +284 -0
  14. package/dist/flow-experimental.mjs.map +1 -0
  15. package/dist/flow.cjs +296 -0
  16. package/dist/flow.cjs.map +1 -0
  17. package/dist/flow.d.cts +79 -0
  18. package/dist/flow.d.cts.map +1 -0
  19. package/dist/flow.d.mts +79 -0
  20. package/dist/flow.d.mts.map +1 -0
  21. package/dist/flow.mjs +294 -0
  22. package/dist/flow.mjs.map +1 -0
  23. package/dist/index.cjs +26 -11
  24. package/dist/index.d.cts +8 -3
  25. package/dist/index.d.mts +8 -3
  26. package/dist/index.mjs +8 -3
  27. package/dist/match.cjs +282 -0
  28. package/dist/match.cjs.map +1 -1
  29. package/dist/match.d.cts +471 -5
  30. package/dist/match.d.cts.map +1 -1
  31. package/dist/match.d.mts +471 -5
  32. package/dist/match.d.mts.map +1 -1
  33. package/dist/match.mjs +277 -1
  34. package/dist/match.mjs.map +1 -1
  35. package/dist/option-experimental.cjs +1503 -0
  36. package/dist/option-experimental.cjs.map +1 -0
  37. package/dist/option-experimental.d.cts +1383 -0
  38. package/dist/option-experimental.d.cts.map +1 -0
  39. package/dist/option-experimental.d.mts +1383 -0
  40. package/dist/option-experimental.d.mts.map +1 -0
  41. package/dist/option-experimental.mjs +1501 -0
  42. package/dist/option-experimental.mjs.map +1 -0
  43. package/dist/option.cjs +556 -29
  44. package/dist/option.cjs.map +1 -1
  45. package/dist/option.d.cts +505 -24
  46. package/dist/option.d.cts.map +1 -1
  47. package/dist/option.d.mts +505 -24
  48. package/dist/option.d.mts.map +1 -1
  49. package/dist/option.mjs +556 -30
  50. package/dist/option.mjs.map +1 -1
  51. package/dist/result-experimental.cjs +1266 -0
  52. package/dist/result-experimental.cjs.map +1 -0
  53. package/dist/result-experimental.d.cts +1127 -0
  54. package/dist/result-experimental.d.cts.map +1 -0
  55. package/dist/result-experimental.d.mts +1127 -0
  56. package/dist/result-experimental.d.mts.map +1 -0
  57. package/dist/result-experimental.mjs +1265 -0
  58. package/dist/result-experimental.mjs.map +1 -0
  59. package/dist/result.cjs +715 -122
  60. package/dist/result.cjs.map +1 -1
  61. package/dist/result.d.cts +785 -94
  62. package/dist/result.d.cts.map +1 -1
  63. package/dist/result.d.mts +785 -94
  64. package/dist/result.d.mts.map +1 -1
  65. package/dist/result.mjs +714 -117
  66. package/dist/result.mjs.map +1 -1
  67. package/dist/tuple.cjs +3 -0
  68. package/dist/tuple.cjs.map +1 -1
  69. package/dist/tuple.d.cts +5 -1
  70. package/dist/tuple.d.cts.map +1 -1
  71. package/dist/tuple.d.mts +5 -1
  72. package/dist/tuple.d.mts.map +1 -1
  73. package/dist/tuple.mjs +2 -0
  74. package/dist/tuple.mjs.map +1 -1
  75. package/dist/unit.cjs +2 -0
  76. package/dist/unit.cjs.map +1 -1
  77. package/dist/unit.d.cts +2 -0
  78. package/dist/unit.d.cts.map +1 -1
  79. package/dist/unit.d.mts +2 -0
  80. package/dist/unit.d.mts.map +1 -1
  81. package/dist/unit.mjs +1 -0
  82. package/dist/unit.mjs.map +1 -1
  83. package/dist/utils.cjs +15 -0
  84. package/dist/utils.cjs.map +1 -1
  85. package/dist/utils.d.cts +10 -1
  86. package/dist/utils.d.cts.map +1 -1
  87. package/dist/utils.d.mts +10 -1
  88. package/dist/utils.d.mts.map +1 -1
  89. package/dist/utils.mjs +13 -1
  90. package/dist/utils.mjs.map +1 -1
  91. package/examples/README.md +46 -0
  92. package/examples/flow/01-basics.ts +74 -0
  93. package/examples/flow/02-async.ts +73 -0
  94. package/examples/flow/03-recovery.ts +60 -0
  95. package/examples/flow/04-complex-backend.ts +237 -0
  96. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  97. package/examples/flow/index.ts +13 -0
  98. package/examples/flow-experimental/01-basics.ts +78 -0
  99. package/examples/flow-experimental/02-async.ts +77 -0
  100. package/examples/flow-experimental/03-recovery.ts +93 -0
  101. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  102. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  103. package/examples/flow-experimental/index.ts +14 -0
  104. package/examples/match/01-stable-match.ts +147 -0
  105. package/examples/match/index.ts +19 -0
  106. package/examples/match-experimental/01-experimental-match.ts +150 -0
  107. package/examples/match-experimental/index.ts +18 -0
  108. package/examples/option/01-basics.ts +16 -0
  109. package/examples/option/02-map-flatMap.ts +36 -0
  110. package/examples/option/03-zip-flatZip.ts +23 -0
  111. package/examples/option/04-constructors.ts +21 -0
  112. package/examples/option/05-transform.ts +15 -0
  113. package/examples/option/06-aggregation.ts +14 -0
  114. package/examples/option/index.ts +49 -0
  115. package/examples/option-experimental/01-map.ts +109 -0
  116. package/examples/option-experimental/02-flatMap.ts +234 -0
  117. package/examples/option-experimental/03-zip.ts +197 -0
  118. package/examples/option-experimental/04-flatZip.ts +251 -0
  119. package/examples/option-experimental/05-gen.ts +360 -0
  120. package/examples/option-experimental/06-genAdapter.ts +463 -0
  121. package/examples/option-experimental/07-asyncGen.ts +353 -0
  122. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  123. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  124. package/examples/option-experimental/10-workflow-async.ts +378 -0
  125. package/examples/option-experimental/index.ts +341 -0
  126. package/examples/option-experimental/shared-domain.ts +325 -0
  127. package/examples/result/01-basics.ts +16 -0
  128. package/examples/result/02-map-flatMap.ts +34 -0
  129. package/examples/result/03-zip-flatZip.ts +23 -0
  130. package/examples/result/04-validation.ts +44 -0
  131. package/examples/result/05-constructors.ts +30 -0
  132. package/examples/result/06-utilities.ts +36 -0
  133. package/examples/result/index.ts +53 -0
  134. package/examples/result-experimental/01-map.ts +60 -0
  135. package/examples/result-experimental/02-flatMap.ts +169 -0
  136. package/examples/result-experimental/03-zip.ts +145 -0
  137. package/examples/result-experimental/04-flatZip.ts +252 -0
  138. package/examples/result-experimental/05-gen.ts +293 -0
  139. package/examples/result-experimental/06-genAdapter.ts +396 -0
  140. package/examples/result-experimental/07-asyncGen.ts +379 -0
  141. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  142. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  143. package/examples/result-experimental/10-workflow-async.ts +356 -0
  144. package/examples/result-experimental/index.ts +312 -0
  145. package/examples/result-experimental/shared-domain.ts +263 -0
  146. package/package.json +50 -18
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Complex Backend Example - User Enrichment Service
3
+ *
4
+ * Demonstrates:
5
+ * - Orchestrating multiple async services (Database, External APIs)
6
+ * - Error handling with custom typed errors
7
+ * - Mixing Result (fallible) and Option (nullable) types
8
+ * - Using Flow.asyncGenAdapter for clean, declarative control flow
9
+ * - Uses ExperimentalOption and ExperimentalResult
10
+ */
11
+
12
+ import {
13
+ ExperimentalFlow as Flow,
14
+ ExperimentalOption as Option,
15
+ ExperimentalResult as Result,
16
+ } from "../../dist/index.mjs"
17
+
18
+ // ============================================================================
19
+ // 1. Domain Types & Errors
20
+ // ============================================================================
21
+
22
+ type UserID = number
23
+
24
+ interface User {
25
+ id: UserID
26
+ username: string
27
+ email: string
28
+ isActive: boolean
29
+ }
30
+
31
+ interface UserPreferences {
32
+ theme: "light" | "dark" | "system"
33
+ notificationsEnabled: boolean
34
+ }
35
+
36
+ interface Order {
37
+ id: string
38
+ total: number
39
+ status: "pending" | "completed"
40
+ }
41
+
42
+ interface EnrichedUser {
43
+ user: User
44
+ preferences: UserPreferences
45
+ recentOrders: Order[]
46
+ lifetimeValue: number
47
+ }
48
+
49
+ // Custom Errors
50
+ class NotFoundError extends Error {
51
+ readonly _tag = "NotFoundError"
52
+ constructor(message: string) {
53
+ super(message)
54
+ this.name = "NotFoundError"
55
+ }
56
+ }
57
+
58
+ class ValidationError extends Error {
59
+ readonly _tag = "ValidationError"
60
+ constructor(message: string) {
61
+ super(message)
62
+ this.name = "ValidationError"
63
+ }
64
+ }
65
+
66
+ class ServiceUnavailableError extends Error {
67
+ readonly _tag = "ServiceUnavailableError"
68
+ constructor(service: string) {
69
+ super(`${service} unavailable`)
70
+ this.name = "ServiceUnavailableError"
71
+ }
72
+ }
73
+
74
+ // ============================================================================
75
+ // 2. Mock Services
76
+ // ============================================================================
77
+
78
+ const DB = {
79
+ users: new Map<UserID, User>([
80
+ [
81
+ 1,
82
+ {
83
+ id: 1,
84
+ username: "alice_w",
85
+ email: "alice@example.com",
86
+ isActive: true,
87
+ },
88
+ ],
89
+ [
90
+ 2,
91
+ {
92
+ id: 2,
93
+ username: "bob_builder",
94
+ email: "bob@example.com",
95
+ isActive: false,
96
+ },
97
+ ],
98
+ ]),
99
+ prefs: new Map<UserID, UserPreferences>([
100
+ [1, { theme: "dark", notificationsEnabled: true }],
101
+ ]),
102
+ }
103
+
104
+ const UserRepository = {
105
+ findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
106
+ // Simulate DB latency
107
+ await new Promise((r) => setTimeout(r, 10))
108
+
109
+ const user = DB.users.get(id)
110
+ return user
111
+ ? Result.Ok(user)
112
+ : Result.Err(new NotFoundError(`User ${id} not found`))
113
+ },
114
+ }
115
+
116
+ const PreferencesService = {
117
+ getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
118
+ await new Promise((r) => setTimeout(r, 10))
119
+ return Option.fromNullable(DB.prefs.get(id))
120
+ },
121
+ }
122
+
123
+ const OrderService = {
124
+ getRecentOrders: async (
125
+ id: UserID,
126
+ ): Promise<Result<Order[], ServiceUnavailableError>> => {
127
+ await new Promise((r) => setTimeout(r, 20))
128
+
129
+ // Simulate random service failure for demo
130
+ if (Math.random() < 0.1) {
131
+ return Result.Err(new ServiceUnavailableError("OrderService"))
132
+ }
133
+
134
+ if (id === 1) {
135
+ return Result.Ok([
136
+ { id: "ord_123", total: 100, status: "completed" },
137
+ { id: "ord_456", total: 49.99, status: "pending" },
138
+ ])
139
+ }
140
+ return Result.Ok([])
141
+ },
142
+ }
143
+
144
+ // ============================================================================
145
+ // 3. Main Logic: Enriched User Fow
146
+ // ============================================================================
147
+
148
+ // Default preferences if none found
149
+ const DEFAULT_PREFS: UserPreferences = {
150
+ theme: "system",
151
+ notificationsEnabled: false,
152
+ }
153
+
154
+ const enrichUser = (userId: number) =>
155
+ Flow.asyncGenAdapter(async function* ($) {
156
+ // 1. Validation Logic (Synchronous Result)
157
+ if (userId <= 0) {
158
+ yield* $(Result.Err(new ValidationError("User ID must be positive")))
159
+ }
160
+
161
+ // 2. Fetch User (Async Result)
162
+ // The adapter automatically awaits the Promise and unwraps the Result
163
+ console.log(`[Flow] Fetching user ${userId}...`)
164
+ const user = yield* $(UserRepository.findById(userId))
165
+
166
+ // 3. Early exit if inactive
167
+ if (!user.isActive) {
168
+ yield* $(Result.Err(new ValidationError("User is inactive")))
169
+ }
170
+
171
+ // 4. Fetch Preferences (Async Option) & Orders (Async Result) in parallel
172
+ // We can use Promise.all to fetch them concurrently, then yield* to unwrap
173
+ console.log(`[Flow] Fetching details for ${user.username}...`)
174
+
175
+ const [prefsOpt, ordersRes] = await Promise.all([
176
+ PreferencesService.getPreferences(user.id),
177
+ OrderService.getRecentOrders(user.id),
178
+ ])
179
+
180
+ // Unwrap Orders (Result) - will bubble up ServiceUnavailableError if failed
181
+ const orders = yield* $(ordersRes)
182
+
183
+ // Unwrap Preferences (Option) - we want to provide a default if None,
184
+ // rather than halting the flow (which yielding a None would do).
185
+ // So we DON'T use yield* on the Option directly here.
186
+ const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
187
+
188
+ // 5. Aggregate Data
189
+ const lifetimeValue = orders.reduce(
190
+ (sum, ord) => (ord.status === "completed" ? sum + ord.total : sum),
191
+ 0,
192
+ )
193
+
194
+ const enriched: EnrichedUser = {
195
+ user,
196
+ preferences,
197
+ recentOrders: orders,
198
+ lifetimeValue,
199
+ }
200
+
201
+ return enriched
202
+ })
203
+
204
+ // ============================================================================
205
+ // 4. Execution Examples
206
+ // ============================================================================
207
+
208
+ async function runDemo() {
209
+ console.log("--- Scenario 1: Happy Path (Alice) ---")
210
+ const res1 = await enrichUser(1)
211
+ /*
212
+ * We can match on the final result to handle success/failure
213
+ */
214
+ res1.match({
215
+ Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
216
+ Err: (err) => console.error("FAILURE:", err.message),
217
+ })
218
+
219
+ console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
220
+ const res2 = await enrichUser(99)
221
+ console.log(
222
+ "Result:",
223
+ res2.isErr() ? `Left(${res2.unwrapErr().message})` : "Ok",
224
+ )
225
+
226
+ console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
227
+ const res3 = await enrichUser(-5)
228
+ console.log(
229
+ "Result:",
230
+ res3.isErr() ? `Left(${res3.unwrapErr().message})` : "Ok",
231
+ )
232
+
233
+ console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
234
+ const res4 = await enrichUser(2)
235
+ console.log(
236
+ "Result:",
237
+ res4.isErr() ? `Left(${res4.unwrapErr().message})` : "Ok",
238
+ )
239
+ }
240
+
241
+ runDemo().catch(console.error)
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Complex Backend Example - User Enrichment Service
3
+ *
4
+ * Demonstrates:
5
+ * - Orchestrating multiple async services (Database, External APIs)
6
+ * - Error handling with custom typed errors using FlowError
7
+ * - Mixing Result (fallible) and Option (nullable) types
8
+ * - Using Flow.asyncGen with direct error yielding via FlowError
9
+ * - Uses ExperimentalOption and ExperimentalResult
10
+ */
11
+
12
+ import {
13
+ ExperimentalFlow as Flow,
14
+ ExperimentalFlowError as FlowError,
15
+ ExperimentalOption as Option,
16
+ ExperimentalResult as Result,
17
+ } from "../../src/index.js"
18
+
19
+ // ============================================================================
20
+ // 1. Domain Types & Errors
21
+ // ============================================================================
22
+
23
+ type UserID = number
24
+
25
+ interface User {
26
+ id: UserID
27
+ username: string
28
+ email: string
29
+ isActive: boolean
30
+ }
31
+
32
+ interface UserPreferences {
33
+ theme: "light" | "dark" | "system"
34
+ notificationsEnabled: boolean
35
+ }
36
+
37
+ interface Order {
38
+ id: string
39
+ total: number
40
+ status: "pending" | "completed"
41
+ }
42
+
43
+ interface EnrichedUser {
44
+ user: User
45
+ preferences: UserPreferences
46
+ recentOrders: Order[]
47
+ lifetimeValue: number
48
+ }
49
+
50
+ // Custom Errors - extend FlowError for direct yielding in Flow generators
51
+ class NotFoundError extends FlowError {
52
+ readonly _tag = "NotFoundError"
53
+ constructor(message: string) {
54
+ super(message)
55
+ Object.defineProperty(this, "name", { value: "NotFoundError" })
56
+ }
57
+ }
58
+
59
+ class ValidationError extends FlowError {
60
+ readonly _tag = "ValidationError"
61
+ constructor(message: string) {
62
+ super(message)
63
+ Object.defineProperty(this, "name", { value: "ValidationError" })
64
+ }
65
+ }
66
+
67
+ class ServiceUnavailableError extends FlowError {
68
+ readonly _tag = "ServiceUnavailableError"
69
+ constructor(service: string) {
70
+ super(`${service} unavailable`)
71
+ Object.defineProperty(this, "name", { value: "ServiceUnavailableError" })
72
+ }
73
+ }
74
+
75
+ // ============================================================================
76
+ // 2. Mock Services
77
+ // ============================================================================
78
+
79
+ const DB = {
80
+ users: new Map<UserID, User>([
81
+ [
82
+ 1,
83
+ {
84
+ id: 1,
85
+ username: "alice_w",
86
+ email: "alice@example.com",
87
+ isActive: true,
88
+ },
89
+ ],
90
+ [
91
+ 2,
92
+ {
93
+ id: 2,
94
+ username: "bob_builder",
95
+ email: "bob@example.com",
96
+ isActive: false,
97
+ },
98
+ ],
99
+ ]),
100
+ prefs: new Map<UserID, UserPreferences>([
101
+ [1, { theme: "dark", notificationsEnabled: true }],
102
+ ]),
103
+ }
104
+
105
+ const UserRepository = {
106
+ findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
107
+ // Simulate DB latency
108
+ await new Promise((r) => setTimeout(r, 10))
109
+
110
+ const user = DB.users.get(id)
111
+ return user
112
+ ? Result.Ok(user)
113
+ : Result.Err(new NotFoundError(`User ${id} not found`))
114
+ },
115
+ }
116
+
117
+ const PreferencesService = {
118
+ getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
119
+ await new Promise((r) => setTimeout(r, 10))
120
+ return Option.fromNullable(DB.prefs.get(id))
121
+ },
122
+ }
123
+
124
+ const OrderService = {
125
+ getRecentOrders: async (
126
+ id: UserID,
127
+ ): Promise<Result<Order[], ServiceUnavailableError>> => {
128
+ await new Promise((r) => setTimeout(r, 20))
129
+
130
+ // Simulate random service failure for demo
131
+ if (Math.random() < 0.1) {
132
+ return Result.Err(new ServiceUnavailableError("OrderService"))
133
+ }
134
+
135
+ if (id === 1) {
136
+ return Result.Ok([
137
+ { id: "ord_123", total: 100, status: "completed" },
138
+ { id: "ord_456", total: 49.99, status: "pending" },
139
+ ])
140
+ }
141
+ return Result.Ok([])
142
+ },
143
+ }
144
+
145
+ // ============================================================================
146
+ // 3. Main Logic: Enriched User Fow
147
+ // ============================================================================
148
+
149
+ // Default preferences if none found
150
+ const DEFAULT_PREFS: UserPreferences = {
151
+ theme: "system",
152
+ notificationsEnabled: false,
153
+ }
154
+
155
+ const enrichUser = async (userId: number) => {
156
+ return await Flow.asyncGen(async function* () {
157
+ // Direct error yielding with FlowError - no Result.Err wrapper needed!
158
+ if (userId <= 0) {
159
+ yield* new ValidationError("UserID must be positive")
160
+ }
161
+
162
+ console.log(`[Flow] Fetching user ${userId}...`)
163
+ const user = yield* await UserRepository.findById(userId)
164
+
165
+ if (!user.isActive) {
166
+ yield* new ValidationError("User account is inactive")
167
+ }
168
+
169
+ console.log(`[Flow] Fetching details for ${user.username}...`)
170
+
171
+ const orders = yield* await OrderService.getRecentOrders(user.id)
172
+
173
+ const prefsOpt = await PreferencesService.getPreferences(user.id)
174
+ const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
175
+
176
+ const lifetimeValue = orders.reduce(
177
+ (sum, order) => (order.status === "completed" ? sum + order.total : sum),
178
+ 0,
179
+ )
180
+
181
+ const enrichedUser: EnrichedUser = {
182
+ user,
183
+ preferences,
184
+ recentOrders: orders,
185
+ lifetimeValue,
186
+ }
187
+
188
+ return enrichedUser
189
+ })
190
+ }
191
+
192
+ // ============================================================================
193
+ // 4. Execution Examples
194
+ // ============================================================================
195
+
196
+ async function runDemo() {
197
+ console.log("--- Scenario 1: Happy Path (Alice) ---")
198
+ const res1 = await enrichUser(1)
199
+ /*
200
+ * We can match on the final result to handle success/failure
201
+ */
202
+ res1.match({
203
+ Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
204
+ Err: (err) => console.error("FAILURE:", (err as Error).message),
205
+ })
206
+
207
+ console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
208
+ const res2 = await enrichUser(99)
209
+ console.log(
210
+ "Result:",
211
+ res2.isErr() ? `Left(${(res2.unwrapErr() as Error).message})` : "Ok",
212
+ )
213
+
214
+ console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
215
+ const res3 = await enrichUser(-5)
216
+ console.log(
217
+ "Result:",
218
+ res3.isErr() ? `Left(${(res3.unwrapErr() as Error).message})` : "Ok",
219
+ )
220
+
221
+ console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
222
+ const res4 = await enrichUser(2)
223
+ console.log(
224
+ "Result:",
225
+ res4.isErr() ? `Left(${(res4.unwrapErr() as Error).message})` : "Ok",
226
+ )
227
+ }
228
+
229
+ runDemo().catch(console.error)
@@ -0,0 +1,14 @@
1
+ /**
2
+ * ExperimentalFlow Examples Index
3
+ *
4
+ * These examples use the experimental Flow API with
5
+ * ExperimentalOption and ExperimentalResult.
6
+ * Run examples with:
7
+ * bun run examples/flow-experimental/01-basics.ts
8
+ * bun run examples/flow-experimental/02-async.ts
9
+ * bun run examples/flow-experimental/03-recovery.ts
10
+ * bun run examples/flow-experimental/04-complex-backend.ts
11
+ * bun run examples/flow-experimental/05-complex-backend-asyncGen.ts
12
+ */
13
+
14
+ export {}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * match() API examples for stable Option/Result.
3
+ *
4
+ * This file demonstrates:
5
+ * - String-tag matching
6
+ * - Pattern helpers (P.Some/P.Ok/etc)
7
+ * - Guards and fallthrough
8
+ * - Generic discriminated unions
9
+ * - How to handle Option<Promise<T>> / Result<Promise<T>, E>
10
+ */
11
+
12
+ import { match, P } from "../../dist/match.mjs"
13
+ import { Option } from "../../dist/option.mjs"
14
+ import { Result } from "../../dist/result.mjs"
15
+
16
+ console.log("=== Stable match() examples ===\n")
17
+
18
+ // -----------------------------------------------------------------------------
19
+ // 1) Basic Option/Result matching
20
+ // -----------------------------------------------------------------------------
21
+
22
+ const maybeScore = Option.Some(82)
23
+ const grade = match(maybeScore)
24
+ .with("Some", (value) => (value >= 90 ? "A" : "B"))
25
+ .with("None", () => "N/A")
26
+ .exhaustive()
27
+ console.log("grade:", grade)
28
+
29
+ const apiResult = Result.Err("rate-limited") as Result<number, string>
30
+ const label = match(apiResult)
31
+ .with("Ok", (value) => `value=${value}`)
32
+ .with("Err", (error) => `error=${error}`)
33
+ .exhaustive()
34
+ console.log("result label:", label)
35
+
36
+ // -----------------------------------------------------------------------------
37
+ // 2) P helpers + guards
38
+ // -----------------------------------------------------------------------------
39
+
40
+ const guarded = match(Option.Some(74))
41
+ .with(
42
+ P.Some((x: number) => x >= 90),
43
+ () => "A",
44
+ )
45
+ .with(
46
+ P.Some((x: number) => x >= 80),
47
+ () => "B",
48
+ )
49
+ .with(
50
+ P.Some((x: number) => x >= 70),
51
+ () => "C",
52
+ )
53
+ .with(P.Some(), () => "D")
54
+ .with(P.None(), () => "N/A")
55
+ .exhaustive()
56
+ console.log("guarded grade:", guarded)
57
+
58
+ const retryPolicy = match(Result.Err("fatal") as Result<number, string>)
59
+ .with(P.Ok(), () => "none")
60
+ .with(P.Err(P.oneOf("timeout", "offline")), () => "retry")
61
+ .with(P.Err(P.not(P.oneOf("timeout", "offline"))), () => "do-not-retry")
62
+ .exhaustive()
63
+ console.log("retry policy:", retryPolicy)
64
+
65
+ const stateByPredicates = match(Result.Ok(1) as Result<number, string>)
66
+ .when(P.IsErr, () => "err")
67
+ .when(P.IsOk, () => "ok")
68
+ .otherwise(() => "other")
69
+ console.log("state by predicates:", stateByPredicates)
70
+
71
+ const combinedPredicates = match(Result.Ok(42) as Result<number, string>)
72
+ .with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
73
+ .with(P.Ok(), () => "miss")
74
+ .with(P.Err(), () => "err")
75
+ .exhaustive()
76
+ console.log("combined predicates:", combinedPredicates)
77
+
78
+ // -----------------------------------------------------------------------------
79
+ // 3) when() + otherwise() + wildcard
80
+ // -----------------------------------------------------------------------------
81
+
82
+ const status = match(Result.Ok({ attempts: 4, user: "alice" }))
83
+ .when(
84
+ (r) => r.isOk() && r.unwrap().attempts > 3,
85
+ () => "needs-review",
86
+ )
87
+ .with(P._, () => "ok")
88
+ .exhaustive()
89
+ console.log("status:", status)
90
+
91
+ const fallbackStatus = match(Result.Err("boom") as Result<number, string>)
92
+ .with(P.Ok(P.not(P.eq(42))), () => "ok-not-42")
93
+ .with(P.Ok(P.eq(42)), () => "ok-42")
94
+ .otherwise(() => "fallback")
95
+ console.log("fallback status:", fallbackStatus)
96
+
97
+ // -----------------------------------------------------------------------------
98
+ // 4) Generic discriminated union support
99
+ // -----------------------------------------------------------------------------
100
+
101
+ type JobEvent =
102
+ | { readonly _tag: "queued"; id: string }
103
+ | { readonly _tag: "running"; id: string; progress: number }
104
+ | { readonly _tag: "failed"; id: string; reason: string }
105
+
106
+ const asJobEvent = (value: JobEvent): JobEvent => value
107
+ const event = asJobEvent({ _tag: "running", id: "job-1", progress: 55 })
108
+ const eventText = match(event)
109
+ .with("queued", (e) => `queued:${e.id}`)
110
+ .with("running", (e) => `running:${e.id}:${e.progress}%`)
111
+ .with("failed", (e) => `failed:${e.id}:${e.reason}`)
112
+ .exhaustive()
113
+ console.log("event:", eventText)
114
+
115
+ // -----------------------------------------------------------------------------
116
+ // 5) Async-inner stable values: settle first, then match
117
+ // -----------------------------------------------------------------------------
118
+
119
+ async function runAsyncInnerExamples(): Promise<void> {
120
+ // IMPORTANT:
121
+ // match() intentionally rejects Result<Promise<T>, E> and Option<Promise<T>>.
122
+ // For stable variants, convert them first with toPromise():
123
+ // Result<Promise<T>, E> -> Promise<Result<T, E>>
124
+ // Option<Promise<T>> -> Promise<Option<T>>
125
+
126
+ const asyncStableResult = Result.Ok(Promise.resolve(21))
127
+ const settledResult = await asyncStableResult.toPromise()
128
+
129
+ const settledResultText = match(settledResult)
130
+ .with("Ok", (value) => `settled-ok:${value * 2}`)
131
+ .with("Err", (error) => `settled-err:${String(error)}`)
132
+ .exhaustive()
133
+ console.log("settled result:", settledResultText)
134
+
135
+ const asyncStableOption = Option.Some(Promise.resolve("token-123"))
136
+ const settledOption = await asyncStableOption.toPromise()
137
+
138
+ const settledOptionText = match(settledOption)
139
+ .with("Some", (value) => `settled-some:${value}`)
140
+ .with("None", () => "settled-none")
141
+ .exhaustive()
142
+ console.log("settled option:", settledOptionText)
143
+ }
144
+
145
+ await runAsyncInnerExamples()
146
+
147
+ console.log("\n=== stable match() examples complete ===")
@@ -0,0 +1,19 @@
1
+ /**
2
+ * match() Examples Index (Stable)
3
+ *
4
+ * Run:
5
+ * bun run examples/match/01-stable-match.ts
6
+ */
7
+
8
+ /**
9
+ * 01-stable-match.ts
10
+ *
11
+ * Topics covered:
12
+ * - match() with stable Option/Result
13
+ * - P helpers and guarded cases
14
+ * - wildcard/when/otherwise
15
+ * - generic discriminated unions
16
+ * - async-inner stable values via toPromise()
17
+ */
18
+
19
+ export {}