@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,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.genAdapter() - Generator with adapter for better type inference
|
|
3
|
+
*
|
|
4
|
+
* genAdapter() works like gen() but provides an adapter function ($)
|
|
5
|
+
* for improved type inference, especially with complex error types.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// BASIC GENADAPTER EXAMPLES
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
console.log("=== Result.genAdapter() Examples ===\n")
|
|
15
|
+
|
|
16
|
+
// Example 1: Simple genAdapter with adapter function
|
|
17
|
+
const simple = Result.genAdapter(function* ($) {
|
|
18
|
+
const value = yield* $(Result.Ok(42))
|
|
19
|
+
return value
|
|
20
|
+
})
|
|
21
|
+
console.log("1. Simple genAdapter:", simple.unwrap()) // 42
|
|
22
|
+
|
|
23
|
+
// Example 2: Multiple yields with adapter
|
|
24
|
+
const multiple = Result.genAdapter(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: genAdapter improves type inference with different error types
|
|
32
|
+
type Error1 = { type: "error1"; message: string }
|
|
33
|
+
type Error2 = { type: "error2"; message: string }
|
|
34
|
+
|
|
35
|
+
const operation1 = (n: number): Result<number, Error1> => {
|
|
36
|
+
return n > 0
|
|
37
|
+
? Result.Ok(n)
|
|
38
|
+
: Result.Err({ type: "error1", message: "Not positive" })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const operation2 = (n: number): Result<number, Error2> => {
|
|
42
|
+
return n < 100
|
|
43
|
+
? Result.Ok(n)
|
|
44
|
+
: Result.Err({ type: "error2", message: "Too large" })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const combined = Result.genAdapter(function* ($) {
|
|
48
|
+
const a = yield* $(Result.Ok(50))
|
|
49
|
+
const b = yield* $(operation1(a))
|
|
50
|
+
const c = yield* $(operation2(b))
|
|
51
|
+
return c
|
|
52
|
+
})
|
|
53
|
+
// Type is Result<number, Error1 | Error2>
|
|
54
|
+
console.log("3. Combined error types:", combined.unwrap()) // 50
|
|
55
|
+
|
|
56
|
+
// Example 4: genAdapter for validation with rich error types
|
|
57
|
+
type ValidationError =
|
|
58
|
+
| { field: "email"; code: "INVALID_FORMAT" }
|
|
59
|
+
| { field: "email"; code: "REQUIRED" }
|
|
60
|
+
| { field: "password"; code: "TOO_SHORT" }
|
|
61
|
+
| { field: "password"; code: "NO_NUMBER" }
|
|
62
|
+
|
|
63
|
+
const validateEmail = (email: string): Result<string, ValidationError> => {
|
|
64
|
+
if (!email) return Result.Err({ field: "email", code: "REQUIRED" })
|
|
65
|
+
if (!email.includes("@"))
|
|
66
|
+
return Result.Err({ field: "email", code: "INVALID_FORMAT" })
|
|
67
|
+
return Result.Ok(email)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const validatePassword = (
|
|
71
|
+
password: string,
|
|
72
|
+
): Result<string, ValidationError> => {
|
|
73
|
+
if (password.length < 8)
|
|
74
|
+
return Result.Err({ field: "password", code: "TOO_SHORT" })
|
|
75
|
+
if (!/\d/.test(password))
|
|
76
|
+
return Result.Err({ field: "password", code: "NO_NUMBER" })
|
|
77
|
+
return Result.Ok(password)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const validateCredentials = (email: string, password: string) => {
|
|
81
|
+
return Result.genAdapter(function* ($) {
|
|
82
|
+
const validEmail = yield* $(validateEmail(email))
|
|
83
|
+
const validPassword = yield* $(validatePassword(password))
|
|
84
|
+
return { email: validEmail, password: validPassword }
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
console.log(
|
|
88
|
+
"4. Valid credentials:",
|
|
89
|
+
validateCredentials("user@example.com", "pass1234").unwrap(),
|
|
90
|
+
) // { email: "user@example.com", password: "pass1234" }
|
|
91
|
+
console.log(
|
|
92
|
+
" Invalid email:",
|
|
93
|
+
validateCredentials("invalid", "pass123").unwrapErr(),
|
|
94
|
+
) // { field: "email", code: "INVALID_FORMAT" }
|
|
95
|
+
|
|
96
|
+
// Example 5: genAdapter with method calls on objects
|
|
97
|
+
class Counter {
|
|
98
|
+
constructor(private value: number = 0) {}
|
|
99
|
+
|
|
100
|
+
increment(): Result<number, "overflow"> {
|
|
101
|
+
if (this.value >= Number.MAX_SAFE_INTEGER) {
|
|
102
|
+
return Result.Err("overflow")
|
|
103
|
+
}
|
|
104
|
+
this.value++
|
|
105
|
+
return Result.Ok(this.value)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
decrement(): Result<number, "underflow"> {
|
|
109
|
+
if (this.value <= Number.MIN_SAFE_INTEGER) {
|
|
110
|
+
return Result.Err("underflow")
|
|
111
|
+
}
|
|
112
|
+
this.value--
|
|
113
|
+
return Result.Ok(this.value)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
getValue() {
|
|
117
|
+
return this.value
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const counterOps = Result.genAdapter(function* ($) {
|
|
122
|
+
const counter = new Counter(0)
|
|
123
|
+
|
|
124
|
+
const a = yield* $(counter.increment())
|
|
125
|
+
const b = yield* $(counter.increment())
|
|
126
|
+
const c = yield* $(counter.decrement())
|
|
127
|
+
|
|
128
|
+
return { a, b, c, final: counter.getValue() }
|
|
129
|
+
})
|
|
130
|
+
console.log("5. Counter ops:", counterOps.unwrap()) // { a: 1, b: 2, c: 1, final: 1 }
|
|
131
|
+
|
|
132
|
+
// Example 6: genAdapter for API composition
|
|
133
|
+
type ApiError = { status: number; message: string }
|
|
134
|
+
|
|
135
|
+
const fetchUser = (
|
|
136
|
+
id: number,
|
|
137
|
+
): Result<{ id: number; name: string }, ApiError> => {
|
|
138
|
+
return Result.Ok({ id, name: `User ${id}` })
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const fetchSettings = (
|
|
142
|
+
_userId: number,
|
|
143
|
+
): Result<{ theme: string }, ApiError> => {
|
|
144
|
+
return Result.Ok({ theme: "dark" })
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const fetchPreferences = (
|
|
148
|
+
_userId: number,
|
|
149
|
+
): Result<{ language: string }, ApiError> => {
|
|
150
|
+
return Result.Ok({ language: "en" })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const fetchUserData = (userId: number) => {
|
|
154
|
+
return Result.genAdapter(function* ($) {
|
|
155
|
+
const user = yield* $(fetchUser(userId))
|
|
156
|
+
const settings = yield* $(fetchSettings(user.id))
|
|
157
|
+
const preferences = yield* $(fetchPreferences(user.id))
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
user,
|
|
161
|
+
settings,
|
|
162
|
+
preferences,
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
console.log("6. Fetch user data:", fetchUserData(1).unwrap()) // { user: { id: 1, name: "User 1" }, settings: { theme: "dark" }, preferences: { language: "en" } }
|
|
167
|
+
|
|
168
|
+
// Example 7: genAdapter with conditional logic
|
|
169
|
+
const conditional = Result.genAdapter(function* ($) {
|
|
170
|
+
const input = yield* $(Result.Ok(5))
|
|
171
|
+
|
|
172
|
+
if (input > 0) {
|
|
173
|
+
const doubled = yield* $(Result.Ok(input * 2))
|
|
174
|
+
return { value: doubled, source: "doubled" as const }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { value: input, source: "original" as const }
|
|
178
|
+
})
|
|
179
|
+
console.log("7. Conditional:", conditional.unwrap()) // { value: 10, source: "doubled" }
|
|
180
|
+
|
|
181
|
+
// Example 8: genAdapter for parallel-like operations (sequential but cleaner)
|
|
182
|
+
const processData = Result.genAdapter(function* ($) {
|
|
183
|
+
const step1 = yield* $(Result.Ok("raw data"))
|
|
184
|
+
const step2 = yield* $(Result.Ok(step1.toUpperCase()))
|
|
185
|
+
const step3 = yield* $(Result.Ok(step2.trim()))
|
|
186
|
+
const step4 = yield* $(Result.Ok(step3.split(" ")))
|
|
187
|
+
return step4
|
|
188
|
+
})
|
|
189
|
+
console.log("8. Process data:", processData.unwrap()) // ["RAW", "DATA"]
|
|
190
|
+
|
|
191
|
+
// Example 9: genAdapter with error type narrowing
|
|
192
|
+
type HttpError =
|
|
193
|
+
| { type: "network"; message: string }
|
|
194
|
+
| { type: "timeout"; message: string }
|
|
195
|
+
| { type: "server"; status: number }
|
|
196
|
+
|
|
197
|
+
const fetchData = (): Result<string, HttpError> => {
|
|
198
|
+
return Result.Ok("data")
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const processDataWithError = () => {
|
|
202
|
+
return Result.genAdapter(function* ($) {
|
|
203
|
+
const data = yield* $(fetchData())
|
|
204
|
+
|
|
205
|
+
// Error type is narrowed to HttpError here
|
|
206
|
+
return data.toUpperCase()
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
console.log("9. Process with error:", processDataWithError().unwrap()) // "DATA"
|
|
210
|
+
|
|
211
|
+
// Example 10: genAdapter for building complex state
|
|
212
|
+
interface State {
|
|
213
|
+
user: { id: number; name: string } | null
|
|
214
|
+
config: { theme: string } | null
|
|
215
|
+
data: string[] | null
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const buildState = () =>
|
|
219
|
+
Result.genAdapter(function* ($) {
|
|
220
|
+
const state: State = {
|
|
221
|
+
user: null,
|
|
222
|
+
config: null,
|
|
223
|
+
data: null,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
state.user = yield* $(fetchUser(1))
|
|
227
|
+
state.config = yield* $(fetchSettings(state.user.id))
|
|
228
|
+
state.data = yield* $(Result.Ok(["item1", "item2"]))
|
|
229
|
+
|
|
230
|
+
return state
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
console.log("10. Build state:", buildState().unwrap()) // { user: { id: 1, name: "User 1" }, config: { theme: "dark" }, data: ["item1", "item2"] }
|
|
234
|
+
|
|
235
|
+
// Example 11: genAdapter with try-catch pattern
|
|
236
|
+
const safeParseInt = (str: string): Result<number, "parse_error"> => {
|
|
237
|
+
const parsed = parseInt(str, 10)
|
|
238
|
+
return Number.isNaN(parsed) ? Result.Err("parse_error") : Result.Ok(parsed)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const safeDivide = (a: number, b: number): Result<number, "divide_by_zero"> => {
|
|
242
|
+
return b !== 0 ? Result.Ok(a / b) : Result.Err("divide_by_zero")
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const safeCalculate = (aStr: string, bStr: string) => {
|
|
246
|
+
return Result.genAdapter(function* ($) {
|
|
247
|
+
const a = yield* $(safeParseInt(aStr))
|
|
248
|
+
const b = yield* $(safeParseInt(bStr))
|
|
249
|
+
const result = yield* $(safeDivide(a, b))
|
|
250
|
+
return result
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
console.log("11. Safe calculate:", safeCalculate("10", "2").unwrap()) // 5
|
|
254
|
+
console.log(" Divide by zero:", safeCalculate("10", "0").unwrapErr()) // "divide_by_zero"
|
|
255
|
+
|
|
256
|
+
// Example 12: genAdapter with array iteration
|
|
257
|
+
const processArray = () =>
|
|
258
|
+
Result.genAdapter(function* ($) {
|
|
259
|
+
const numbers = yield* $(Result.Ok([1, 2, 3, 4, 5]))
|
|
260
|
+
const results: number[] = []
|
|
261
|
+
|
|
262
|
+
for (const num of numbers) {
|
|
263
|
+
const doubled = yield* $(Result.Ok(num * 2))
|
|
264
|
+
results.push(doubled)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return results
|
|
268
|
+
})
|
|
269
|
+
console.log("12. Process array:", processArray().unwrap()) // [2, 4, 6, 8, 10]
|
|
270
|
+
|
|
271
|
+
// Example 13: genAdapter for multi-step validation
|
|
272
|
+
type FieldValidation =
|
|
273
|
+
| { field: "username"; error: "TOO_SHORT" | "INVALID_CHARS" }
|
|
274
|
+
| { field: "email"; error: "INVALID_FORMAT" }
|
|
275
|
+
| { field: "age"; error: "TOO_YOUNG" }
|
|
276
|
+
|
|
277
|
+
const validateUsername = (
|
|
278
|
+
username: string,
|
|
279
|
+
): Result<string, FieldValidation> => {
|
|
280
|
+
if (username.length < 3)
|
|
281
|
+
return Result.Err({ field: "username", error: "TOO_SHORT" })
|
|
282
|
+
if (!/^[a-zA-Z0-9]+$/.test(username))
|
|
283
|
+
return Result.Err({ field: "username", error: "INVALID_CHARS" })
|
|
284
|
+
return Result.Ok(username)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const validateAge = (age: number): Result<number, FieldValidation> => {
|
|
288
|
+
if (age < 18) return Result.Err({ field: "age", error: "TOO_YOUNG" })
|
|
289
|
+
return Result.Ok(age)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const registerUser = (username: string, age: number) => {
|
|
293
|
+
return Result.genAdapter(function* ($) {
|
|
294
|
+
const validUsername = yield* $(validateUsername(username))
|
|
295
|
+
const validAge = yield* $(validateAge(age))
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
username: validUsername,
|
|
299
|
+
age: validAge,
|
|
300
|
+
registered: true,
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
}
|
|
304
|
+
console.log("13. Register user:", registerUser("alice123", 25).unwrap()) // { username: "alice123", age: 25, registered: true }
|
|
305
|
+
console.log(" Invalid username:", registerUser("ab", 25).unwrapErr()) // { field: "username", error: "TOO_SHORT" }
|
|
306
|
+
|
|
307
|
+
// Example 14: genAdapter for nested Result operations
|
|
308
|
+
const nested = Result.genAdapter(function* ($) {
|
|
309
|
+
const outer = yield* $(Result.Ok(5))
|
|
310
|
+
|
|
311
|
+
// Nested genAdapter call
|
|
312
|
+
const inner = Result.genAdapter(function* ($) {
|
|
313
|
+
const a = yield* $(Result.Ok(outer))
|
|
314
|
+
const b = yield* $(Result.Ok(a * 2))
|
|
315
|
+
return b
|
|
316
|
+
})
|
|
317
|
+
|
|
318
|
+
return yield* $(inner)
|
|
319
|
+
})
|
|
320
|
+
console.log("14. Nested:", nested.unwrap()) // 10
|
|
321
|
+
|
|
322
|
+
// Example 15: genAdapter with accumulator
|
|
323
|
+
const sumWithAdapter = Result.genAdapter(function* ($) {
|
|
324
|
+
const numbers = yield* $(Result.Ok([1, 2, 3, 4, 5]))
|
|
325
|
+
let sum = 0
|
|
326
|
+
|
|
327
|
+
for (const num of numbers) {
|
|
328
|
+
sum += num
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return sum
|
|
332
|
+
})
|
|
333
|
+
console.log("15. Sum with adapter:", sumWithAdapter.unwrap()) // 15
|
|
334
|
+
|
|
335
|
+
// Example 16: genAdapter vs gen - same behavior, different syntax
|
|
336
|
+
const genResult = Result.gen(function* () {
|
|
337
|
+
const a = yield* Result.Ok(1)
|
|
338
|
+
const b = yield* Result.Ok(2)
|
|
339
|
+
return a + b
|
|
340
|
+
})
|
|
341
|
+
|
|
342
|
+
const adapterResult = Result.genAdapter(function* ($) {
|
|
343
|
+
const a = yield* $(Result.Ok(1))
|
|
344
|
+
const b = yield* $(Result.Ok(2))
|
|
345
|
+
return a + b
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
console.log("16. gen:", genResult.unwrap()) // 3
|
|
349
|
+
console.log(" genAdapter:", adapterResult.unwrap()) // 3
|
|
350
|
+
|
|
351
|
+
// Example 17: genAdapter for transaction-like operations
|
|
352
|
+
type TransactionError =
|
|
353
|
+
| { type: "insufficient_funds"; balance: number; required: number }
|
|
354
|
+
| { type: "account_not_found"; id: number }
|
|
355
|
+
|
|
356
|
+
interface Account {
|
|
357
|
+
id: number
|
|
358
|
+
balance: number
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const getAccount = (id: number): Result<Account, TransactionError> => {
|
|
362
|
+
if (id === 999) return Result.Err({ type: "account_not_found", id })
|
|
363
|
+
return Result.Ok({ id, balance: 100 })
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const checkBalance = (
|
|
367
|
+
account: Account,
|
|
368
|
+
amount: number,
|
|
369
|
+
): Result<Account, TransactionError> => {
|
|
370
|
+
if (account.balance < amount) {
|
|
371
|
+
return Result.Err({
|
|
372
|
+
type: "insufficient_funds",
|
|
373
|
+
balance: account.balance,
|
|
374
|
+
required: amount,
|
|
375
|
+
})
|
|
376
|
+
}
|
|
377
|
+
return Result.Ok(account)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const transferFunds = (fromId: number, toId: number, amount: number) => {
|
|
381
|
+
return Result.genAdapter(function* ($) {
|
|
382
|
+
const fromAccount = yield* $(getAccount(fromId))
|
|
383
|
+
const toAccount = yield* $(getAccount(toId))
|
|
384
|
+
const validatedFrom = yield* $(checkBalance(fromAccount, amount))
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
from: { ...validatedFrom, balance: validatedFrom.balance - amount },
|
|
388
|
+
to: { ...toAccount, balance: toAccount.balance + amount },
|
|
389
|
+
amount,
|
|
390
|
+
}
|
|
391
|
+
})
|
|
392
|
+
}
|
|
393
|
+
console.log("17. Transfer funds:", transferFunds(1, 2, 50).unwrap()) // { from: { id: 1, balance: 50 }, to: { id: 2, balance: 150 }, amount: 50 }
|
|
394
|
+
console.log(" Insufficient funds:", transferFunds(1, 2, 200).unwrapErr()) // { type: "insufficient_funds", balance: 100, required: 200 }
|
|
395
|
+
|
|
396
|
+
console.log("\n=== All genAdapter examples completed ===")
|