@carbonteq/fp 0.9.1 → 0.11.1
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 +326 -97
- package/dist/errors.cjs +2 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -5
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts +2 -5
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs +1 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +332 -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 +330 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +340 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +77 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +77 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +338 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +29 -14
- package/dist/index.d.cts +10 -5
- package/dist/index.d.mts +10 -5
- package/dist/index.mjs +10 -5
- package/dist/match.cjs +376 -3
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +467 -8
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +467 -8
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +371 -3
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1547 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1380 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1380 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1545 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +650 -71
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +528 -39
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +528 -39
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +648 -70
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1346 -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 +1345 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +746 -81
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +799 -104
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +799 -104
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +742 -73
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +5 -4
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +9 -7
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +9 -7
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +4 -3
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +3 -3
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +4 -5
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +4 -5
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +2 -2
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +50 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +14 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +14 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +46 -3
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +60 -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 +240 -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 +244 -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 +154 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +157 -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 +54 -31
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.flatZip() - Pair original with value from another Result
|
|
3
|
+
*
|
|
4
|
+
* flatZip() is like zip() but the function returns a Result.
|
|
5
|
+
* It pairs the original value with the unwrapped value from the Result.
|
|
6
|
+
* If either Result is Err, the error propagates.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC FLATZIP EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Result.flatZip() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Basic flatZip - pair value with Result-returning function
|
|
18
|
+
const flatZipped = Result.Ok(5).flatZip((x) => Result.Ok(x * 2))
|
|
19
|
+
console.log("1. FlatZip 5 with Result.Ok(10):", flatZipped.unwrap()) // [5, 10]
|
|
20
|
+
|
|
21
|
+
// Example 2: flatZip with Err - error propagates
|
|
22
|
+
const flatZippedErr = Result.Ok(5).flatZip((_x) => Result.Err("error"))
|
|
23
|
+
console.log("2. FlatZip with Err:", flatZippedErr.unwrapErr()) // "error"
|
|
24
|
+
|
|
25
|
+
// Example 3: flatZip on initial Err - short-circuits
|
|
26
|
+
const initialErr = Result.Err<string, number>("initial").flatZip((x) =>
|
|
27
|
+
Result.Ok(x * 2),
|
|
28
|
+
)
|
|
29
|
+
console.log("3. FlatZip on initial Err:", initialErr.unwrapErr()) // "initial"
|
|
30
|
+
|
|
31
|
+
// Example 4: Chaining flatZips - accumulate values
|
|
32
|
+
const chained = Result.Ok(1)
|
|
33
|
+
.flatZip((a) => Result.Ok(a + 1)) // [1, 2]
|
|
34
|
+
.flatZip(([a, b]) => Result.Ok(a + b)) // [[1, 2], 3]
|
|
35
|
+
|
|
36
|
+
console.log("4. Chained flatZip:", chained.unwrap()) // [[1, 2], 3]
|
|
37
|
+
|
|
38
|
+
// Example 5: flatZip is synchronous - for async operations, use gen.async* methods
|
|
39
|
+
// See 07-asyncGen.ts and 08-asyncGenAdapter.ts for async patterns
|
|
40
|
+
|
|
41
|
+
// Example 6: Practical - User and their posts
|
|
42
|
+
type UserId = number
|
|
43
|
+
type User = { id: UserId; name: string }
|
|
44
|
+
type Post = { id: number; authorId: UserId; title: string }
|
|
45
|
+
|
|
46
|
+
const getUser = (id: UserId): Result<User, "user_not_found"> => {
|
|
47
|
+
return Result.Ok({ id, name: `User ${id}` })
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const getUserPosts = (user: User): Result<Post[], "posts_error"> => {
|
|
51
|
+
return Result.Ok([{ id: 1, authorId: user.id, title: `${user.name}'s Post` }])
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const userWithPosts = getUser(1).flatZip((user) => getUserPosts(user))
|
|
55
|
+
console.log("6. User with posts:", userWithPosts.unwrap()) // [{ id: 1, name: "User 1" }, [{ ... }]]
|
|
56
|
+
|
|
57
|
+
// Example 7: flatZip for dependent lookups
|
|
58
|
+
type ProductId = number
|
|
59
|
+
type Product = { id: ProductId; name: string; price: number }
|
|
60
|
+
type Inventory = { productId: ProductId; quantity: number }
|
|
61
|
+
|
|
62
|
+
const getProduct = (id: ProductId): Result<Product, "product_not_found"> => {
|
|
63
|
+
return Result.Ok({ id, name: "Widget", price: 10 })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const getInventory = (
|
|
67
|
+
product: Product,
|
|
68
|
+
): Result<Inventory, "inventory_not_found"> => {
|
|
69
|
+
return Result.Ok({ productId: product.id, quantity: 100 })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const productWithInventory = getProduct(1).flatZip((product) =>
|
|
73
|
+
getInventory(product),
|
|
74
|
+
)
|
|
75
|
+
console.log("7. Product with inventory:", productWithInventory.unwrap()) // [{ id: 1, name: "Widget", price: 10 }, { productId: 1, quantity: 100 }]
|
|
76
|
+
|
|
77
|
+
// Example 8: flatZip for validation with context preservation
|
|
78
|
+
type ValidationError = { field: string; message: string }
|
|
79
|
+
|
|
80
|
+
const validateEmailBasic = (email: string): Result<string, ValidationError> => {
|
|
81
|
+
return email.includes("@")
|
|
82
|
+
? Result.Ok(email)
|
|
83
|
+
: Result.Err({ field: "email", message: "Invalid email" })
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const normalizeEmail = (email: string): Result<string, ValidationError> => {
|
|
87
|
+
return Result.Ok(email.toLowerCase().trim())
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const emailWithValidation = Result.Ok("USER@EXAMPLE.COM")
|
|
91
|
+
.flatZip((email) => normalizeEmail(email))
|
|
92
|
+
.flatZip(([_original, normalized]) => validateEmailBasic(normalized))
|
|
93
|
+
|
|
94
|
+
console.log("8. Email validation chain:", emailWithValidation.unwrap()) // [["USER@EXAMPLE.COM", "user@example.com"], "user@example.com"]
|
|
95
|
+
|
|
96
|
+
// Example 9: flatMap for building complex objects step by step
|
|
97
|
+
// Use flatMap when you don't need to preserve the intermediate value
|
|
98
|
+
type Address = { street: string; city: string }
|
|
99
|
+
type Person = { name: string; age: number }
|
|
100
|
+
|
|
101
|
+
const validatePerson = (data: {
|
|
102
|
+
name: string
|
|
103
|
+
age: number
|
|
104
|
+
}): Result<Person, ValidationError> => {
|
|
105
|
+
return data.age >= 18
|
|
106
|
+
? Result.Ok(data)
|
|
107
|
+
: Result.Err({ field: "age", message: "Must be 18 or older" })
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const fetchAddress = (_person: Person): Result<Address, ValidationError> => {
|
|
111
|
+
return Result.Ok({ street: "123 Main St", city: "Anytown" })
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const createPersonWithAddress = (data: { name: string; age: number }) => {
|
|
115
|
+
return validatePerson(data).flatMap((person) =>
|
|
116
|
+
fetchAddress(person).map((address) => ({
|
|
117
|
+
...person,
|
|
118
|
+
address,
|
|
119
|
+
})),
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
console.log(
|
|
124
|
+
"9. Person with address:",
|
|
125
|
+
createPersonWithAddress({ name: "Alice", age: 25 }).unwrap(),
|
|
126
|
+
) // { name: "Alice", age: 25, address: { street: "123 Main St", city: "Anytown" } }
|
|
127
|
+
|
|
128
|
+
// Example 10: flatZip vs flatMap - preserving original
|
|
129
|
+
const flatMapResult = Result.Ok(5).flatMap((x) => Result.Ok(x * 2)) // Result<number, never>
|
|
130
|
+
const flatZipResult = Result.Ok(5).flatZip((x) => Result.Ok(x * 2)) // Result<[5, 10], never>
|
|
131
|
+
|
|
132
|
+
console.log("10. flatMap loses original:", flatMapResult.unwrap()) // 10
|
|
133
|
+
console.log(" flatZip preserves:", flatZipResult.unwrap()) // [5, 10]
|
|
134
|
+
|
|
135
|
+
// Example 11: flatZip for collecting audit trail
|
|
136
|
+
type AuditLog<T> = { timestamp: number; data: T }
|
|
137
|
+
|
|
138
|
+
const withAudit = <T, E>(result: Result<T, E>): Result<[T, AuditLog<T>], E> => {
|
|
139
|
+
const timestamp = Date.now()
|
|
140
|
+
return result.flatZip((data) => Result.Ok({ timestamp, data }))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const auditedResult = withAudit(Result.Ok({ value: 42 }))
|
|
144
|
+
console.log("11. Audited result:", auditedResult.unwrap()) // [{ value: 42 }, { timestamp: ..., data: { value: 42 } }]
|
|
145
|
+
|
|
146
|
+
// Example 12: flatZip for maintaining context through transformations
|
|
147
|
+
type Context<T> = { original: T; current: T }
|
|
148
|
+
|
|
149
|
+
const withContext = <T>(value: T): Result<Context<T>, never> => {
|
|
150
|
+
return Result.Ok({ original: value, current: value })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const transformWithContext = <T, E>(
|
|
154
|
+
context: Result<Context<T>, E>,
|
|
155
|
+
fn: (value: T) => Result<T, E>,
|
|
156
|
+
): Result<Context<T>, E> => {
|
|
157
|
+
return context.flatMap((ctx) =>
|
|
158
|
+
fn(ctx.current).map((newCurrent) => ({
|
|
159
|
+
original: ctx.original,
|
|
160
|
+
current: newCurrent,
|
|
161
|
+
})),
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const result = transformWithContext(withContext(10), (n) =>
|
|
166
|
+
Result.Ok(n * 2),
|
|
167
|
+
).flatMap((ctx) =>
|
|
168
|
+
transformWithContext(Result.Ok(ctx), (n) => Result.Ok(n + 5)),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
console.log("12. Context through transformations:", result.unwrap()) // { original: 10, current: 25 }
|
|
172
|
+
|
|
173
|
+
// Example 13: flatZip for branching logic
|
|
174
|
+
const getConfig = (key: string): Result<string, "config_not_found"> => {
|
|
175
|
+
const configs: Record<string, string> = {
|
|
176
|
+
api_key: "secret123",
|
|
177
|
+
timeout: "5000",
|
|
178
|
+
}
|
|
179
|
+
const value = configs[key]
|
|
180
|
+
return value ? Result.Ok(value) : Result.Err("config_not_found")
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const parseTimeout = (
|
|
184
|
+
timeoutStr: string,
|
|
185
|
+
): Result<number, "invalid_timeout"> => {
|
|
186
|
+
const parsed = parseInt(timeoutStr, 10)
|
|
187
|
+
return Number.isNaN(parsed)
|
|
188
|
+
? Result.Err("invalid_timeout")
|
|
189
|
+
: Result.Ok(parsed)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const getConfigValue = (
|
|
193
|
+
key: string,
|
|
194
|
+
): Result<[string, number], "config_not_found" | "invalid_timeout"> => {
|
|
195
|
+
return getConfig(key).flatZip((value) => parseTimeout(value))
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
console.log("13. Config value:", getConfigValue("timeout").unwrap()) // ["5000", 5000]
|
|
199
|
+
console.log(" Invalid config:", getConfigValue("api_key").unwrapErr()) // "invalid_timeout" (because "secret123" is not a number)
|
|
200
|
+
|
|
201
|
+
// Example 14: flatZip for multi-step validation pipeline
|
|
202
|
+
type ValidationResult<T> = Result<T, ValidationError>
|
|
203
|
+
|
|
204
|
+
interface UserData {
|
|
205
|
+
email: string
|
|
206
|
+
password: string
|
|
207
|
+
age: number
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const validateUserData = (data: UserData): ValidationResult<UserData> => {
|
|
211
|
+
return Result.Ok(data)
|
|
212
|
+
.flatMap((data) => validateEmail(data.email).map(() => data))
|
|
213
|
+
.flatMap((data) => validatePassword(data.password).map(() => data))
|
|
214
|
+
.flatMap((data) => validateAge(data.age).map(() => data))
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const validateEmail = (email: string): ValidationResult<string> => {
|
|
218
|
+
return email.includes("@")
|
|
219
|
+
? Result.Ok(email)
|
|
220
|
+
: Result.Err({ field: "email", message: "Invalid" })
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const validatePassword = (password: string): ValidationResult<string> => {
|
|
224
|
+
return password.length >= 8
|
|
225
|
+
? Result.Ok(password)
|
|
226
|
+
: Result.Err({ field: "password", message: "Too short" })
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const validateAge = (age: number): ValidationResult<number> => {
|
|
230
|
+
return age >= 18
|
|
231
|
+
? Result.Ok(age)
|
|
232
|
+
: Result.Err({ field: "age", message: "Too young" })
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
console.log(
|
|
236
|
+
"14. Valid user:",
|
|
237
|
+
validateUserData({
|
|
238
|
+
email: "test@example.com",
|
|
239
|
+
password: "password123",
|
|
240
|
+
age: 25,
|
|
241
|
+
}).unwrap(),
|
|
242
|
+
) // { email: "test@example.com", password: "password123", age: 25 }
|
|
243
|
+
console.log(
|
|
244
|
+
" Invalid email:",
|
|
245
|
+
validateUserData({
|
|
246
|
+
email: "invalid",
|
|
247
|
+
password: "password123",
|
|
248
|
+
age: 25,
|
|
249
|
+
}).unwrapErr(),
|
|
250
|
+
) // { field: "email", message: "Invalid" }
|
|
251
|
+
|
|
252
|
+
console.log("\n=== All flatZip examples completed ===")
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.gen() - Generator-based syntax for Result composition
|
|
3
|
+
*
|
|
4
|
+
* Result.gen() provides imperative-style code while maintaining
|
|
5
|
+
* functional error handling. Short-circuits on first Err.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// BASIC GEN EXAMPLES
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
console.log("=== Result.gen() Examples ===\n")
|
|
15
|
+
|
|
16
|
+
// Example 1: Simple gen with single yield
|
|
17
|
+
const simple = Result.gen(function* () {
|
|
18
|
+
const value = yield* Result.Ok(42)
|
|
19
|
+
return value
|
|
20
|
+
})
|
|
21
|
+
console.log("1. Simple gen:", simple.unwrap()) // 42
|
|
22
|
+
|
|
23
|
+
// Example 2: Multiple yields - sequence operations
|
|
24
|
+
const multiple = Result.gen(function* () {
|
|
25
|
+
const a = yield* Result.Ok(5)
|
|
26
|
+
const b = yield* Result.Ok(10)
|
|
27
|
+
return a + b
|
|
28
|
+
})
|
|
29
|
+
console.log("2. Multiple yields:", multiple.unwrap()) // 15
|
|
30
|
+
|
|
31
|
+
// Example 3: Short-circuit on first Err
|
|
32
|
+
const shortCircuit = Result.gen(function* () {
|
|
33
|
+
const a = yield* Result.Ok(5)
|
|
34
|
+
const b = yield* Result.Err<string, number>("error")
|
|
35
|
+
const c = yield* Result.Ok(10) // This is never reached
|
|
36
|
+
return a + b + c
|
|
37
|
+
})
|
|
38
|
+
console.log("3. Short-circuit:", shortCircuit.unwrapErr()) // "error"
|
|
39
|
+
|
|
40
|
+
// Example 4: gen with function calls
|
|
41
|
+
const fetchValue = (key: string): Result<number, "not_found"> => {
|
|
42
|
+
if (key === "valid") return Result.Ok(42)
|
|
43
|
+
return Result.Err("not_found")
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const withFetch = Result.gen(function* () {
|
|
47
|
+
const a = yield* fetchValue("valid")
|
|
48
|
+
const b = yield* fetchValue("valid")
|
|
49
|
+
return a + b
|
|
50
|
+
})
|
|
51
|
+
console.log("4. With fetch:", withFetch.unwrap()) // 84
|
|
52
|
+
|
|
53
|
+
// Example 5: gen for validation pipeline
|
|
54
|
+
const validatePositive = (n: number): Result<number, "not_positive"> => {
|
|
55
|
+
return n > 0 ? Result.Ok(n) : Result.Err("not_positive")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const validateEven = (n: number): Result<number, "not_even"> => {
|
|
59
|
+
return n % 2 === 0 ? Result.Ok(n) : Result.Err("not_even")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const validate = Result.gen(function* () {
|
|
63
|
+
const input = yield* Result.Ok(4)
|
|
64
|
+
const positive = yield* validatePositive(input)
|
|
65
|
+
const even = yield* validateEven(positive)
|
|
66
|
+
return even * 2
|
|
67
|
+
})
|
|
68
|
+
console.log("5. Validation pipeline:", validate.unwrap()) // 8
|
|
69
|
+
|
|
70
|
+
// Example 6: gen vs flatMap readability
|
|
71
|
+
// flatMap version (nested)
|
|
72
|
+
const flatMapVersion = Result.Ok(5).flatMap((a) =>
|
|
73
|
+
Result.Ok(a * 2).flatMap((b) => Result.Ok(b + 10)),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
// gen version (linear)
|
|
77
|
+
const genVersion = Result.gen(function* () {
|
|
78
|
+
const a = yield* Result.Ok(5)
|
|
79
|
+
const b = yield* Result.Ok(a * 2)
|
|
80
|
+
return b + 10
|
|
81
|
+
})
|
|
82
|
+
console.log("6. flatMap:", flatMapVersion.unwrap()) // 20
|
|
83
|
+
console.log(" gen:", genVersion.unwrap()) // 20
|
|
84
|
+
|
|
85
|
+
// Example 7: gen for complex object building
|
|
86
|
+
interface User {
|
|
87
|
+
id: number
|
|
88
|
+
name: string
|
|
89
|
+
email: string
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const buildUser = Result.gen(function* () {
|
|
93
|
+
const id = yield* Result.Ok(123)
|
|
94
|
+
const name = yield* Result.Ok("Alice")
|
|
95
|
+
const email = yield* Result.Ok("alice@example.com")
|
|
96
|
+
|
|
97
|
+
return { id, name, email } as User
|
|
98
|
+
})
|
|
99
|
+
console.log("7. Build user:", buildUser.unwrap()) // { id: 123, name: "Alice", email: "alice@example.com" }
|
|
100
|
+
|
|
101
|
+
// Example 8: gen with intermediate processing
|
|
102
|
+
const processData = Result.gen(function* () {
|
|
103
|
+
const rawData = yield* Result.Ok(" hello world ")
|
|
104
|
+
const trimmed = rawData.trim()
|
|
105
|
+
const upper = trimmed.toUpperCase()
|
|
106
|
+
const words = upper.split(" ")
|
|
107
|
+
return words
|
|
108
|
+
})
|
|
109
|
+
console.log("8. Process data:", processData.unwrap()) // ["HELLO", "WORLD"]
|
|
110
|
+
|
|
111
|
+
// Example 9: gen with array operations
|
|
112
|
+
const arrayOps = Result.gen(function* () {
|
|
113
|
+
const numbers = yield* Result.Ok([1, 2, 3, 4, 5])
|
|
114
|
+
const doubled = numbers.map((n) => n * 2)
|
|
115
|
+
const filtered = doubled.filter((n) => n > 5)
|
|
116
|
+
const sum = filtered.reduce((a, b) => a + b, 0)
|
|
117
|
+
return sum
|
|
118
|
+
})
|
|
119
|
+
console.log("9. Array operations:", arrayOps.unwrap()) // 24 (6 + 8 + 10)
|
|
120
|
+
|
|
121
|
+
// Example 10: gen for dependent operations
|
|
122
|
+
type UserId = number
|
|
123
|
+
type BasicUser = { id: UserId; name: string }
|
|
124
|
+
type PostId = number
|
|
125
|
+
type Post = { id: PostId; authorId: UserId; title: string }
|
|
126
|
+
|
|
127
|
+
const getUser = (id: UserId): Result<BasicUser, "user_not_found"> => {
|
|
128
|
+
return Result.Ok({ id, name: `User ${id}` })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const getPostsByUser = (user: BasicUser): Result<Post[], "posts_error"> => {
|
|
132
|
+
return Result.Ok([{ id: 1, authorId: user.id, title: `${user.name}'s Post` }])
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const getUserWithPosts = (userId: UserId) => {
|
|
136
|
+
return Result.gen(function* () {
|
|
137
|
+
const user = yield* getUser(userId)
|
|
138
|
+
const posts = yield* getPostsByUser(user)
|
|
139
|
+
return { user, posts }
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
console.log("10. User with posts:", getUserWithPosts(1).unwrap()) // { user: { id: 1, name: "User 1" }, posts: [...] }
|
|
143
|
+
|
|
144
|
+
// Example 11: gen with no yields (just returns value)
|
|
145
|
+
// biome-ignore lint/correctness/useYield: no worries
|
|
146
|
+
const noYields = Result.gen(function* () {
|
|
147
|
+
// oxlint-disable-next-line require-yield
|
|
148
|
+
return 42
|
|
149
|
+
})
|
|
150
|
+
console.log("11. No yields:", noYields.unwrap()) // 42
|
|
151
|
+
|
|
152
|
+
// Example 12: gen for error context collection
|
|
153
|
+
type ValidationError = { field: string; message: string }
|
|
154
|
+
|
|
155
|
+
const validateName = (name: string): Result<string, ValidationError> => {
|
|
156
|
+
return name.length > 0
|
|
157
|
+
? Result.Ok(name)
|
|
158
|
+
: Result.Err({ field: "name", message: "Required" })
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const validateEmail = (email: string): Result<string, ValidationError> => {
|
|
162
|
+
return email.includes("@")
|
|
163
|
+
? Result.Ok(email)
|
|
164
|
+
: Result.Err({ field: "email", message: "Invalid" })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const validateForm = (name: string, email: string) => {
|
|
168
|
+
return Result.gen(function* () {
|
|
169
|
+
const validName = yield* validateName(name)
|
|
170
|
+
const validEmail = yield* validateEmail(email)
|
|
171
|
+
return { name: validName, email: validEmail }
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
console.log(
|
|
175
|
+
"12. Valid form:",
|
|
176
|
+
validateForm("Alice", "alice@example.com").unwrap(),
|
|
177
|
+
) // { name: "Alice", email: "alice@example.com" }
|
|
178
|
+
console.log(" Invalid form:", validateForm("", "invalid").unwrapErr()) // { field: "name", message: "Required" }
|
|
179
|
+
|
|
180
|
+
// Example 13: gen handles many yields without stack overflow
|
|
181
|
+
const manyYields = Result.gen(function* () {
|
|
182
|
+
let sum = 0
|
|
183
|
+
for (let i = 0; i < 100; i++) {
|
|
184
|
+
const value = yield* Result.Ok(i)
|
|
185
|
+
sum += value
|
|
186
|
+
}
|
|
187
|
+
return sum
|
|
188
|
+
})
|
|
189
|
+
console.log("13. Many yields:", manyYields.unwrap()) // 4950 (sum of 0-99)
|
|
190
|
+
|
|
191
|
+
// Example 14: gen with conditional logic
|
|
192
|
+
const conditional = Result.gen(function* () {
|
|
193
|
+
const input = yield* Result.Ok(5)
|
|
194
|
+
if (input > 0) {
|
|
195
|
+
return input * 2
|
|
196
|
+
}
|
|
197
|
+
return input
|
|
198
|
+
})
|
|
199
|
+
console.log("14. Conditional:", conditional.unwrap()) // 10
|
|
200
|
+
|
|
201
|
+
// Example 15: gen with early return on error
|
|
202
|
+
const earlyReturn = Result.gen(function* () {
|
|
203
|
+
const a = yield* Result.Ok(5)
|
|
204
|
+
const b = yield* validatePositive(a)
|
|
205
|
+
const c = yield* validateEven(b)
|
|
206
|
+
|
|
207
|
+
// If we reach here, all validations passed
|
|
208
|
+
return c
|
|
209
|
+
})
|
|
210
|
+
console.log("15. Early return:", earlyReturn.unwrapErr()) // "not_even" (5 is not even)
|
|
211
|
+
|
|
212
|
+
// Example 16: gen for sequential API call pattern
|
|
213
|
+
type Config = { apiKey: string; endpoint: string }
|
|
214
|
+
const fetchConfig = (): Result<Config, "config_error"> => {
|
|
215
|
+
return Result.Ok({ apiKey: "secret", endpoint: "/api" })
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const validateConfig = (config: Config): Result<Config, "invalid_config"> => {
|
|
219
|
+
return config.apiKey.length > 0
|
|
220
|
+
? Result.Ok(config)
|
|
221
|
+
: Result.Err("invalid_config")
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const initialize = () => {
|
|
225
|
+
return Result.gen(function* () {
|
|
226
|
+
const config = yield* fetchConfig()
|
|
227
|
+
const validated = yield* validateConfig(config)
|
|
228
|
+
return { initialized: true, config: validated }
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
console.log("16. Initialize:", initialize().unwrap()) // { initialized: true, config: { apiKey: "secret", endpoint: "/api" } }
|
|
232
|
+
|
|
233
|
+
// Example 17: gen preserves type information through yields
|
|
234
|
+
type NumberResult = Result<number, "error">
|
|
235
|
+
type StringResult = Result<string, "error">
|
|
236
|
+
|
|
237
|
+
const typedPipeline = Result.gen(function* () {
|
|
238
|
+
const num = yield* Result.Ok(42) as NumberResult
|
|
239
|
+
const str = yield* Result.Ok(num.toString()) as StringResult
|
|
240
|
+
return { num, str }
|
|
241
|
+
})
|
|
242
|
+
console.log("17. Typed pipeline:", typedPipeline.unwrap()) // { num: 42, str: "42" }
|
|
243
|
+
|
|
244
|
+
// Example 18: gen with error recovery pattern
|
|
245
|
+
const withFallback = Result.gen(function* () {
|
|
246
|
+
const primary = yield* fetchValue("invalid")
|
|
247
|
+
return primary
|
|
248
|
+
}).orElse(() => Result.Ok(0)) // Fallback to 0 on error
|
|
249
|
+
console.log("18. With fallback:", withFallback.unwrap()) // 0
|
|
250
|
+
|
|
251
|
+
// Example 19: gen for data transformation pipeline
|
|
252
|
+
type RawData = { value: string }
|
|
253
|
+
type ParsedData = { value: number }
|
|
254
|
+
type ValidatedData = { value: number; isValid: true }
|
|
255
|
+
|
|
256
|
+
const parse = (data: RawData): Result<ParsedData, "parse_error"> => {
|
|
257
|
+
const num = Number(data.value)
|
|
258
|
+
return Number.isNaN(num)
|
|
259
|
+
? Result.Err("parse_error")
|
|
260
|
+
: Result.Ok({ value: num })
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const validateRawData = (
|
|
264
|
+
data: ParsedData,
|
|
265
|
+
): Result<ValidatedData, "validation_error"> => {
|
|
266
|
+
return data.value > 0
|
|
267
|
+
? Result.Ok({ value: data.value, isValid: true })
|
|
268
|
+
: Result.Err("validation_error")
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const processRawData = (raw: RawData) => {
|
|
272
|
+
return Result.gen(function* () {
|
|
273
|
+
const parsed = yield* parse(raw)
|
|
274
|
+
const validated = yield* validateRawData(parsed)
|
|
275
|
+
return validated
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
console.log("19. Process raw data:", processRawData({ value: "42" }).unwrap()) // { value: 42, isValid: true }
|
|
279
|
+
|
|
280
|
+
// Example 20: gen with accumulator pattern
|
|
281
|
+
const accumulator = Result.gen(function* () {
|
|
282
|
+
let acc = 0
|
|
283
|
+
const values = yield* Result.Ok([1, 2, 3, 4, 5])
|
|
284
|
+
|
|
285
|
+
for (const value of values) {
|
|
286
|
+
acc += value
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return acc
|
|
290
|
+
})
|
|
291
|
+
console.log("20. Accumulator:", accumulator.unwrap()) // 15
|
|
292
|
+
|
|
293
|
+
console.log("\n=== All gen examples completed ===")
|