@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,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Option.flatMap() - Chain Option-returning functions
|
|
3
|
+
*
|
|
4
|
+
* flatMap() (also known as bind/chain) is used to sequence operations
|
|
5
|
+
* that can return None. If the first Option is None, the subsequent function
|
|
6
|
+
* is NOT called and None propagates.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC FLATMAP EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Option.flatMap() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Simple flatMap chain
|
|
18
|
+
const parseNumber = (str: string): Option<number> => {
|
|
19
|
+
const num = Number(str)
|
|
20
|
+
return Number.isNaN(num) ? Option.None : Option.Some(num)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const validatePositive = (n: number): Option<number> => {
|
|
24
|
+
return n > 0 ? Option.Some(n) : Option.None
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const result = parseNumber("42").flatMap((n) => validatePositive(n))
|
|
28
|
+
console.log("1. Valid chain:", result.unwrap()) // 42
|
|
29
|
+
|
|
30
|
+
// Example 2: Short-circuit on first None
|
|
31
|
+
const errorResult = parseNumber("invalid").flatMap((n) => validatePositive(n))
|
|
32
|
+
console.log("2. Parse error:", errorResult._tag) // "None"
|
|
33
|
+
|
|
34
|
+
// Example 3: Short-circuit on second None
|
|
35
|
+
const errorResult2 = parseNumber("-5").flatMap((n) => validatePositive(n))
|
|
36
|
+
console.log("3. Validation error:", errorResult2._tag) // "None"
|
|
37
|
+
|
|
38
|
+
// Example 4: Chaining multiple flatMaps
|
|
39
|
+
const divide = (a: number, b: number): Option<number> => {
|
|
40
|
+
return b !== 0 ? Option.Some(a / b) : Option.None
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const calculation = Option.Some(100)
|
|
44
|
+
.flatMap((n) => divide(n, 2))
|
|
45
|
+
.flatMap((n) => divide(n, 5))
|
|
46
|
+
.flatMap((n) => validatePositive(n))
|
|
47
|
+
console.log("4. Chain calculations:", calculation.unwrap()) // 10
|
|
48
|
+
|
|
49
|
+
// Example 5: flatMap for fetching/looking up values
|
|
50
|
+
type UserId = number
|
|
51
|
+
type User = { id: UserId; name: string }
|
|
52
|
+
type PostId = number
|
|
53
|
+
type Post = { id: PostId; authorId: UserId; title: string }
|
|
54
|
+
|
|
55
|
+
const users: Map<UserId, User> = new Map([
|
|
56
|
+
[1, { id: 1, name: "Alice" }],
|
|
57
|
+
[2, { id: 2, name: "Bob" }],
|
|
58
|
+
])
|
|
59
|
+
|
|
60
|
+
const posts: Map<PostId, Post> = new Map([
|
|
61
|
+
[101, { id: 101, authorId: 1, title: "Hello" }],
|
|
62
|
+
[102, { id: 102, authorId: 2, title: "World" }],
|
|
63
|
+
])
|
|
64
|
+
|
|
65
|
+
const getUser = (id: UserId): Option<User> => {
|
|
66
|
+
const user = users.get(id)
|
|
67
|
+
return user ? Option.Some(user) : Option.None
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const getPost = (id: PostId): Option<Post> => {
|
|
71
|
+
const post = posts.get(id)
|
|
72
|
+
return post ? Option.Some(post) : Option.None
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const getPostAuthor = (postId: PostId): Option<User> => {
|
|
76
|
+
return getPost(postId).flatMap((post) => getUser(post.authorId))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
console.log("5. Get post author:", getPostAuthor(101).unwrap()) // { id: 1, name: "Alice" }
|
|
80
|
+
|
|
81
|
+
// Example 6: flatMap for validation pipeline
|
|
82
|
+
const requireString = (value: unknown): Option<string> => {
|
|
83
|
+
return typeof value === "string" ? Option.Some(value) : Option.None
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const requireNonEmpty = (str: string): Option<string> => {
|
|
87
|
+
return str.length > 0 ? Option.Some(str) : Option.None
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const validateInput = (value: unknown): Option<string> => {
|
|
91
|
+
return requireString(value).flatMap((str) => requireNonEmpty(str))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
console.log("6. Valid input:", validateInput("hello").unwrap()) // "hello"
|
|
95
|
+
console.log(" Invalid input:", validateInput(123)._tag) // "None"
|
|
96
|
+
|
|
97
|
+
// Example 7: flatMap vs map - when to use which
|
|
98
|
+
const mapExample = Option.Some(5).map((x) => Option.Some(x * 2)) // Option<Option<number>>
|
|
99
|
+
const flatMapExample = Option.Some(5).flatMap((x) => Option.Some(x * 2)) // Option<number>
|
|
100
|
+
|
|
101
|
+
console.log("7. map wraps Option:", mapExample.unwrap().unwrap()) // 10 (need double unwrap)
|
|
102
|
+
console.log(" flatMap flattens:", flatMapExample.unwrap()) // 10 (single unwrap)
|
|
103
|
+
|
|
104
|
+
// Example 8: Practical - User lookup chain
|
|
105
|
+
type Database = {
|
|
106
|
+
users: Map<string, { id: string; name: string; email?: string }>
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const db: Database = {
|
|
110
|
+
users: new Map([
|
|
111
|
+
["user-123", { id: "user-123", name: "Alice", email: "alice@example.com" }],
|
|
112
|
+
["user-456", { id: "user-456", name: "Bob" }], // no email
|
|
113
|
+
]),
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const findUser = (
|
|
117
|
+
id: string,
|
|
118
|
+
): Option<{ id: string; name: string; email?: string }> => {
|
|
119
|
+
const user = db.users.get(id)
|
|
120
|
+
return user ? Option.Some(user) : Option.None
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const getUserEmail = (id: string): Option<string> => {
|
|
124
|
+
return findUser(id).flatMap((user) => Option.fromNullable(user.email))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
console.log("8. User with email:", getUserEmail("user-123").unwrap()) // "alice@example.com"
|
|
128
|
+
console.log(" User without email:", getUserEmail("user-456")._tag) // "None"
|
|
129
|
+
|
|
130
|
+
// Example 9: flatMap is synchronous - for async operations, use gen.async* methods
|
|
131
|
+
// See 07-asyncGen.ts and 08-asyncGenAdapter.ts for async patterns
|
|
132
|
+
|
|
133
|
+
// Example 10: Nested object access with flatMap
|
|
134
|
+
type Address = { street: string; city: string }
|
|
135
|
+
type Company = { name: string; address?: Address }
|
|
136
|
+
type Employee = { name: string; company?: Company }
|
|
137
|
+
|
|
138
|
+
const getEmployeeCity = (employee: Employee): Option<string> => {
|
|
139
|
+
return Option.fromNullable(employee.company)
|
|
140
|
+
.flatMap((company) => Option.fromNullable(company.address))
|
|
141
|
+
.map((address) => address.city)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const emp1: Employee = {
|
|
145
|
+
name: "Alice",
|
|
146
|
+
company: { name: "Acme", address: { street: "123 Main", city: "NYC" } },
|
|
147
|
+
}
|
|
148
|
+
const emp2: Employee = { name: "Bob", company: { name: "Acme" } }
|
|
149
|
+
const emp3: Employee = { name: "Charlie" }
|
|
150
|
+
|
|
151
|
+
console.log("9. Employee with city:", getEmployeeCity(emp1).unwrap()) // "NYC"
|
|
152
|
+
console.log(" Employee without address:", getEmployeeCity(emp2)._tag) // "None"
|
|
153
|
+
console.log(" Employee without company:", getEmployeeCity(emp3)._tag) // "None"
|
|
154
|
+
|
|
155
|
+
// Example 10: flatMap for safe array element access
|
|
156
|
+
const safeGetElement = <T>(arr: T[], index: number): Option<T> => {
|
|
157
|
+
return index >= 0 && index < arr.length
|
|
158
|
+
? Option.Some(arr[index])
|
|
159
|
+
: Option.None
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const getSecondElement = <T>(arr: T[]): Option<T> => {
|
|
163
|
+
return safeGetElement(arr, 1)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
console.log("10. Second element:", getSecondElement([1, 2, 3]).unwrap()) // 2
|
|
167
|
+
console.log(" Out of bounds:", getSecondElement([1])._tag) // "None"
|
|
168
|
+
|
|
169
|
+
// Example 11: flatMap with Option.all
|
|
170
|
+
const getAllUsers = (...ids: UserId[]): Option<User[]> => {
|
|
171
|
+
return Option.all(...ids.map((id) => getUser(id)))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
console.log("11. All users found:", getAllUsers(1, 2).unwrap()) // [{ id: 1, ... }, { id: 2, ... }]
|
|
175
|
+
console.log(" Some users missing:", getAllUsers(1, 999)._tag) // "None"
|
|
176
|
+
|
|
177
|
+
// Example 12: flatMap for parsing and validating JSON
|
|
178
|
+
const safeParseJSON = (json: string): Option<unknown> => {
|
|
179
|
+
try {
|
|
180
|
+
return Option.Some(JSON.parse(json))
|
|
181
|
+
} catch {
|
|
182
|
+
return Option.None
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const validateString = (value: unknown): Option<string> => {
|
|
187
|
+
return typeof value === "string" ? Option.Some(value) : Option.None
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const parseAndValidateString = (json: string): Option<string> => {
|
|
191
|
+
return safeParseJSON(json).flatMap((value) => validateString(value))
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
console.log(
|
|
195
|
+
"12. Valid JSON string:",
|
|
196
|
+
parseAndValidateString('"hello"').unwrap(),
|
|
197
|
+
) // "hello"
|
|
198
|
+
console.log(" Invalid JSON:", parseAndValidateString("invalid")._tag) // "None"
|
|
199
|
+
console.log(" Non-string JSON:", parseAndValidateString("123")._tag) // "None"
|
|
200
|
+
|
|
201
|
+
// Example 13: flatMap for configuration lookup
|
|
202
|
+
type Config = {
|
|
203
|
+
api?: { key?: string; endpoint?: string }
|
|
204
|
+
database?: { host?: string; port?: number }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const config: Config = {
|
|
208
|
+
api: { key: "secret123", endpoint: "https://api.example.com" },
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const getApiEndpoint = (cfg: Config): Option<string> => {
|
|
212
|
+
return Option.fromNullable(cfg.api).flatMap((api) =>
|
|
213
|
+
Option.fromNullable(api.endpoint),
|
|
214
|
+
)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
console.log("13. API endpoint:", getApiEndpoint(config).unwrap()) // "https://api.example.com"
|
|
218
|
+
console.log(
|
|
219
|
+
" Missing endpoint:",
|
|
220
|
+
getApiEndpoint({ api: { key: "test" } })._tag,
|
|
221
|
+
) // "None"
|
|
222
|
+
|
|
223
|
+
// Example 14: flatMap with conditional logic
|
|
224
|
+
const findAdultUser = (id: UserId): Option<User> => {
|
|
225
|
+
return getUser(id).flatMap((user) => {
|
|
226
|
+
// Simulate age check
|
|
227
|
+
const isAdult = true // Assume all users are adults for this example
|
|
228
|
+
return isAdult ? Option.Some(user) : Option.None
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
console.log("14. Adult user:", findAdultUser(1).unwrap()) // { id: 1, name: "Alice" }
|
|
233
|
+
|
|
234
|
+
console.log("\n=== All flatMap examples completed ===")
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Option.zip() - Pair original value with derived value
|
|
3
|
+
*
|
|
4
|
+
* zip() takes a function that receives the current value and returns a new value.
|
|
5
|
+
* It returns an Option containing a tuple [original, derived].
|
|
6
|
+
* Useful when you need both the original and transformed values.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
console.log("=== Option.zip() Examples ===\n")
|
|
12
|
+
|
|
13
|
+
// Example 1: Basic zip - pair value with its double
|
|
14
|
+
const zipped = Option.Some(5).zip((x) => x * 2)
|
|
15
|
+
console.log("1. Zip 5 with double:", zipped.unwrap()) // [5, 10]
|
|
16
|
+
|
|
17
|
+
// Example 2: Zip on None - None propagates
|
|
18
|
+
const zippedNone = Option.None.zip((x: number) => x * 2)
|
|
19
|
+
console.log("2. Zip on None:", zippedNone._tag) // "None"
|
|
20
|
+
|
|
21
|
+
// Example 3: Zip with async function
|
|
22
|
+
const asyncZipped = await Option.Some(5).zipAsync(async (x) => {
|
|
23
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
24
|
+
return x * 2
|
|
25
|
+
})
|
|
26
|
+
console.log("3. Async zip:", asyncZipped._tag) // "Some"
|
|
27
|
+
|
|
28
|
+
const value = asyncZipped.unwrap()
|
|
29
|
+
console.log(" Resolved:", value) // [5, 10]
|
|
30
|
+
|
|
31
|
+
// Example 4: Zip for validation with context
|
|
32
|
+
const parseAndValidate = (str: string) => {
|
|
33
|
+
return Option.fromNullable(Number(str))
|
|
34
|
+
.filter((n) => !Number.isNaN(n))
|
|
35
|
+
.flatZip((num) => (num > 0 ? Option.Some(num) : Option.None))
|
|
36
|
+
.map(([num, _validated]) => ({
|
|
37
|
+
original: str,
|
|
38
|
+
parsed: num,
|
|
39
|
+
isValidated: true,
|
|
40
|
+
}))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
console.log("4. Parse with context:", parseAndValidate("42").unwrap()) // { original: "42", parsed: 42, isValidated: true }
|
|
44
|
+
console.log(" Negative number:", parseAndValidate("-5")._tag) // "None"
|
|
45
|
+
|
|
46
|
+
// Example 5: Multiple zips - accumulate related values
|
|
47
|
+
const userStats = Option.Some(100) // starting score
|
|
48
|
+
.zip((score) => score * 2) // double
|
|
49
|
+
.zip(([original, doubled]) => original + doubled) // sum
|
|
50
|
+
|
|
51
|
+
console.log("5. Multiple zips:", userStats.unwrap()) // [[100, 200], 300]
|
|
52
|
+
|
|
53
|
+
// Example 6: Zip for keeping audit trail
|
|
54
|
+
type Input = { value: number }
|
|
55
|
+
type Output = { result: number }
|
|
56
|
+
type WithAudit<T> = { input: Input; output: T }
|
|
57
|
+
|
|
58
|
+
const processWithAudit = (input: Input): Option<WithAudit<Output>> => {
|
|
59
|
+
return Option.Some(input)
|
|
60
|
+
.zip((input) => ({ result: input.value * 2 }))
|
|
61
|
+
.map(([input, output]) => ({ input, output }))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
console.log("6. Process with audit:", processWithAudit({ value: 5 }).unwrap()) // { input: { value: 5 }, output: { result: 10 } }
|
|
65
|
+
|
|
66
|
+
// Example 7: Zip for before/after comparison
|
|
67
|
+
const beforeAndAfter = Option.Some([1, 2, 3, 4, 5])
|
|
68
|
+
.zip((arr) => arr.filter((x) => x % 2 === 0))
|
|
69
|
+
.map(([original, filtered]) => ({
|
|
70
|
+
original,
|
|
71
|
+
filtered,
|
|
72
|
+
count: { original: original.length, filtered: filtered.length },
|
|
73
|
+
}))
|
|
74
|
+
|
|
75
|
+
console.log("7. Before/after:", beforeAndAfter.unwrap()) // { original: [1,2,3,4,5], filtered: [2,4], count: { original: 5, filtered: 2 } }
|
|
76
|
+
|
|
77
|
+
// Example 8: Zip for transformation history
|
|
78
|
+
type HistoryStep<T> = { step: number; value: T }
|
|
79
|
+
|
|
80
|
+
const withHistory: Option<HistoryStep<number>[]> = Option.Some(5)
|
|
81
|
+
.zip((value) => value * 2)
|
|
82
|
+
.zip(([_original, doubled]) => doubled + 10)
|
|
83
|
+
.map(([[original, doubled], final]) => [
|
|
84
|
+
{ step: 1, value: original },
|
|
85
|
+
{ step: 2, value: doubled },
|
|
86
|
+
{ step: 3, value: final },
|
|
87
|
+
])
|
|
88
|
+
|
|
89
|
+
console.log("8. Transformation history:", withHistory.unwrap()) // [{ step: 1, value: 5 }, { step: 2, value: 10 }, { step: 3, value: 20 }]
|
|
90
|
+
|
|
91
|
+
// Example 9: Practical - Form field validation with original value
|
|
92
|
+
type Field = { name: string; value: string }
|
|
93
|
+
type ValidatedField = { name: string; value: string; isValid: boolean }
|
|
94
|
+
|
|
95
|
+
const validateField = (field: Field): Option<ValidatedField> => {
|
|
96
|
+
return Option.Some(field)
|
|
97
|
+
.flatZip((field) =>
|
|
98
|
+
field.value.length > 0 ? Option.Some(field) : Option.None,
|
|
99
|
+
)
|
|
100
|
+
.map(([original, _]) => ({ ...original, isValid: true }))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
console.log(
|
|
104
|
+
"9. Valid field:",
|
|
105
|
+
validateField({ name: "email", value: "test@example.com" }).unwrap(),
|
|
106
|
+
) // { name: "email", value: "test@example.com", isValid: true }
|
|
107
|
+
console.log(
|
|
108
|
+
" Invalid field:",
|
|
109
|
+
validateField({ name: "email", value: "" })._tag,
|
|
110
|
+
) // "None"
|
|
111
|
+
|
|
112
|
+
// Example 10: Zip for accumulating calculations
|
|
113
|
+
const calculationSteps = Option.Some(10)
|
|
114
|
+
.zip((n) => n + 5) // add
|
|
115
|
+
.zip(([_start, sum]) => sum * 2) // multiply
|
|
116
|
+
.zip(([[start, _sum], product]) => product - start) // subtract
|
|
117
|
+
|
|
118
|
+
console.log("10. Calculation steps:", calculationSteps.unwrap()) // [[[10, 15], 30], 20]
|
|
119
|
+
|
|
120
|
+
// Example 11: Async zip for API call patterns
|
|
121
|
+
const fetchUser = async (id: number) => {
|
|
122
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
123
|
+
return { id, name: `User ${id}` }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const userWithTimestamp = await Option.Some(1)
|
|
127
|
+
.zipAsync((id) => fetchUser(id))
|
|
128
|
+
.then((o) => o.map(([id, user]) => ({ id, user, fetchedAt: Date.now() })))
|
|
129
|
+
|
|
130
|
+
const result2 = userWithTimestamp.unwrap()
|
|
131
|
+
console.log("11. Async fetch with timestamp:", result2) // { id: 1, user: { id: 1, name: "User 1" }, fetchedAt: ... }
|
|
132
|
+
|
|
133
|
+
// Example 12: Zip for pairing input with output
|
|
134
|
+
type ProcessResult<T, U> = { input: T; output: U }
|
|
135
|
+
|
|
136
|
+
const processWithPairing = <T, U>(
|
|
137
|
+
input: T,
|
|
138
|
+
processor: (value: T) => U,
|
|
139
|
+
): Option<ProcessResult<T, U>> => {
|
|
140
|
+
return Option.Some(input)
|
|
141
|
+
.zip(processor)
|
|
142
|
+
.map(([input, output]) => ({ input, output }))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const result = processWithPairing(5, (x) => x * 2)
|
|
146
|
+
console.log("12. Paired processing:", result.unwrap()) // { input: 5, output: 10 }
|
|
147
|
+
|
|
148
|
+
// Example 13: Zip for value with its metadata
|
|
149
|
+
type Metadata<T> = {
|
|
150
|
+
value: T
|
|
151
|
+
length: number
|
|
152
|
+
type: string
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const withMetadata = (value: string): Option<Metadata<string>> => {
|
|
156
|
+
return Option.Some(value)
|
|
157
|
+
.zip((v) => ({
|
|
158
|
+
length: v.length,
|
|
159
|
+
type: typeof v,
|
|
160
|
+
}))
|
|
161
|
+
.map(([value, meta]) => ({ value, ...meta }))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
console.log("13. With metadata:", withMetadata("hello").unwrap()) // { value: "hello", length: 5, type: "string" }
|
|
165
|
+
|
|
166
|
+
// Example 14: Zip for conditional transformation
|
|
167
|
+
const conditionalZip = Option.Some(5)
|
|
168
|
+
.zip((x) => (x > 0 ? x * 2 : x))
|
|
169
|
+
.map(([original, transformed]) => ({
|
|
170
|
+
original,
|
|
171
|
+
transformed,
|
|
172
|
+
changed: original !== transformed,
|
|
173
|
+
}))
|
|
174
|
+
|
|
175
|
+
console.log("14. Conditional zip:", conditionalZip.unwrap()) // { original: 5, transformed: 10, changed: true }
|
|
176
|
+
|
|
177
|
+
// Example 15: Zip for safe division with context
|
|
178
|
+
const safeDivideWithContext = (
|
|
179
|
+
a: number,
|
|
180
|
+
b: number,
|
|
181
|
+
): Option<{ dividend: number; divisor: number; quotient: number }> => {
|
|
182
|
+
const opt = Option.Some({ dividend: a, divisor: b })
|
|
183
|
+
.flatZip(({ divisor }) =>
|
|
184
|
+
divisor !== 0 ? Option.Some(a / divisor) : Option.None,
|
|
185
|
+
)
|
|
186
|
+
.map(([context, quotient]) => ({ ...context, quotient }))
|
|
187
|
+
|
|
188
|
+
return opt
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
console.log("15. Divide with context:", safeDivideWithContext(10, 2).unwrap()) // { dividend: 10, divisor: 2, quotient: 5 }
|
|
192
|
+
console.log(" Divide by zero:", safeDivideWithContext(10, 0)._tag) // "None"
|
|
193
|
+
|
|
194
|
+
console.log("\n=== All zip examples completed ===")
|
|
195
|
+
|
|
196
|
+
// Wait for async examples to complete
|
|
197
|
+
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Option.flatZip() - Pair original with value from another Option
|
|
3
|
+
*
|
|
4
|
+
* flatZip() is like zip() but the function returns an Option.
|
|
5
|
+
* It pairs the original value with the unwrapped value from the Option.
|
|
6
|
+
* If either Option is None, None propagates.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC FLATZIP EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Option.flatZip() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Basic flatZip - pair value with Option-returning function
|
|
18
|
+
const flatZipped = Option.Some(5).flatZip((x) => Option.Some(x * 2))
|
|
19
|
+
console.log("1. FlatZip 5 with Some(10):", flatZipped.unwrap()) // [5, 10]
|
|
20
|
+
|
|
21
|
+
// Example 2: flatZip with None - None propagates
|
|
22
|
+
const flatZippedNone = Option.Some(5).flatZip((_x) => Option.None)
|
|
23
|
+
console.log("2. FlatZip with None:", flatZippedNone._tag) // "None"
|
|
24
|
+
|
|
25
|
+
// Example 3: flatZip on initial None - short-circuits
|
|
26
|
+
const initialNone = Option.None.flatZip((x: number) => Option.Some(x * 2))
|
|
27
|
+
console.log("3. FlatZip on initial None:", initialNone._tag) // "None"
|
|
28
|
+
|
|
29
|
+
// Example 4: Chaining flatZips - accumulate values
|
|
30
|
+
const chained = Option.Some(1)
|
|
31
|
+
.flatZip((a) => Option.Some(a + 1)) // [1, 2]
|
|
32
|
+
.flatZip(([a, b]) => Option.Some(a + b)) // [[1, 2], 3]
|
|
33
|
+
|
|
34
|
+
console.log("4. Chained flatZip:", chained.unwrap()) // [[1, 2], 3]
|
|
35
|
+
|
|
36
|
+
// Example 5: Practical - User and their posts
|
|
37
|
+
type UserId = number
|
|
38
|
+
type User = { id: UserId; name: string }
|
|
39
|
+
type Post = { id: number; authorId: UserId; title: string }
|
|
40
|
+
|
|
41
|
+
const getUser = (id: UserId): Option<User> => {
|
|
42
|
+
return Option.Some({ id, name: `User ${id}` })
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const getUserPosts = (user: User): Option<Post[]> => {
|
|
46
|
+
return Option.Some([
|
|
47
|
+
{ id: 1, authorId: user.id, title: `${user.name}'s Post` },
|
|
48
|
+
])
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const userWithPosts = getUser(1).flatZip((user) => getUserPosts(user))
|
|
52
|
+
console.log("5. User with posts:", userWithPosts.unwrap()) // [{ id: 1, name: "User 1" }, [{ ... }]]
|
|
53
|
+
|
|
54
|
+
// Example 6: flatZip for dependent lookups
|
|
55
|
+
type ProductId = number
|
|
56
|
+
type Product = { id: ProductId; name: string; price: number }
|
|
57
|
+
type Inventory = { productId: ProductId; quantity: number }
|
|
58
|
+
|
|
59
|
+
const getProduct = (id: ProductId): Option<Product> => {
|
|
60
|
+
return Option.Some({ id, name: "Widget", price: 10 })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const getInventory = (product: Product): Option<Inventory> => {
|
|
64
|
+
return Option.Some({ productId: product.id, quantity: 100 })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const productWithInventory = getProduct(1).flatZip((product) =>
|
|
68
|
+
getInventory(product),
|
|
69
|
+
)
|
|
70
|
+
console.log("6. Product with inventory:", productWithInventory.unwrap()) // [{ id: 1, name: "Widget", price: 10 }, { productId: 1, quantity: 100 }]
|
|
71
|
+
|
|
72
|
+
// Example 7: flatZip for validation with context preservation
|
|
73
|
+
const validateEmailBasic = (email: string): Option<string> => {
|
|
74
|
+
return email.includes("@") ? Option.Some(email) : Option.None
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const normalizeEmail = (email: string): Option<string> => {
|
|
78
|
+
return Option.Some(email.toLowerCase().trim())
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const emailWithValidation = Option.Some("USER@EXAMPLE.COM")
|
|
82
|
+
.flatZip((email) => normalizeEmail(email))
|
|
83
|
+
.flatZip(([_original, normalized]) => validateEmailBasic(normalized))
|
|
84
|
+
|
|
85
|
+
console.log("7. Email validation chain:", emailWithValidation.unwrap()) // [["USER@EXAMPLE.COM", "user@example.com"], "user@example.com"]
|
|
86
|
+
|
|
87
|
+
// Example 8: flatZip for building complex objects step by step
|
|
88
|
+
type Address = { street: string; city: string }
|
|
89
|
+
type Person = { name: string; age: number }
|
|
90
|
+
|
|
91
|
+
const validatePerson = (data: {
|
|
92
|
+
name: string
|
|
93
|
+
age: number
|
|
94
|
+
}): Option<Person> => {
|
|
95
|
+
return data.age >= 18 ? Option.Some(data) : Option.None
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const fetchAddress = (_person: Person): Option<Address> => {
|
|
99
|
+
return Option.Some({ street: "123 Main St", city: "Anytown" })
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const createPersonWithAddress = (data: { name: string; age: number }) => {
|
|
103
|
+
return validatePerson(data).flatMap((person) =>
|
|
104
|
+
fetchAddress(person).map((address) => ({
|
|
105
|
+
...person,
|
|
106
|
+
address,
|
|
107
|
+
})),
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
console.log(
|
|
112
|
+
"8. Person with address:",
|
|
113
|
+
createPersonWithAddress({ name: "Alice", age: 25 }).unwrap(),
|
|
114
|
+
) // { name: "Alice", age: 25, address: { street: "123 Main St", city: "Anytown" } }
|
|
115
|
+
|
|
116
|
+
// Example 9: flatZip vs flatMap - preserving original
|
|
117
|
+
const flatMapResult = Option.Some(5).flatMap((x) => Option.Some(x * 2)) // Option<number>
|
|
118
|
+
const flatZipResult = Option.Some(5).flatZip((x) => Option.Some(x * 2)) // Option<[5, 10]>
|
|
119
|
+
|
|
120
|
+
console.log("9. flatMap loses original:", flatMapResult.unwrap()) // 10
|
|
121
|
+
console.log(" flatZip preserves:", flatZipResult.unwrap()) // [5, 10]
|
|
122
|
+
|
|
123
|
+
// Example 10: flatZip for collecting audit trail
|
|
124
|
+
type AuditLog<T> = { timestamp: number; data: T }
|
|
125
|
+
|
|
126
|
+
const withAudit = <T>(option: Option<T>): Option<[T, AuditLog<T>]> => {
|
|
127
|
+
const timestamp = Date.now()
|
|
128
|
+
return option.flatZip((data) => Option.Some({ timestamp, data }))
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const auditedResult = withAudit(Option.Some({ value: 42 }))
|
|
132
|
+
console.log("10. Audited result:", auditedResult.unwrap()) // [{ value: 42 }, { timestamp: ..., data: { value: 42 } }]
|
|
133
|
+
|
|
134
|
+
// Example 11: flatZip for maintaining context through transformations
|
|
135
|
+
type Context<T> = { original: T; current: T }
|
|
136
|
+
|
|
137
|
+
const withContext = <T>(value: T): Option<Context<T>> => {
|
|
138
|
+
return Option.Some({ original: value, current: value })
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const transformWithContext = <T>(
|
|
142
|
+
context: Option<Context<T>>,
|
|
143
|
+
fn: (value: T) => Option<T>,
|
|
144
|
+
): Option<Context<T>> => {
|
|
145
|
+
return context.flatMap((ctx) =>
|
|
146
|
+
fn(ctx.current).map((newCurrent) => ({
|
|
147
|
+
original: ctx.original,
|
|
148
|
+
current: newCurrent,
|
|
149
|
+
})),
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const result2 = transformWithContext(withContext(10), (n) =>
|
|
154
|
+
Option.Some(n * 2),
|
|
155
|
+
).flatMap((ctx) =>
|
|
156
|
+
transformWithContext(Option.Some(ctx), (n) => Option.Some(n + 5)),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
console.log("11. Context through transformations:", result2.unwrap()) // { original: 10, current: 25 }
|
|
160
|
+
|
|
161
|
+
// Example 12: flatZip for branching logic
|
|
162
|
+
const getConfig = (key: string): Option<string> => {
|
|
163
|
+
const configs: Record<string, string> = {
|
|
164
|
+
api_key: "secret123",
|
|
165
|
+
timeout: "5000",
|
|
166
|
+
}
|
|
167
|
+
const value = configs[key]
|
|
168
|
+
return value ? Option.Some(value) : Option.None
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const parseTimeout = (timeoutStr: string): Option<number> => {
|
|
172
|
+
const parsed = parseInt(timeoutStr, 10)
|
|
173
|
+
return Number.isNaN(parsed) ? Option.None : Option.Some(parsed)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const getConfigValue = (key: string): Option<[string, number]> => {
|
|
177
|
+
return getConfig(key).flatZip((value) => parseTimeout(value))
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
console.log("12. Config value:", getConfigValue("timeout").unwrap()) // ["5000", 5000]
|
|
181
|
+
console.log(" Invalid config:", getConfigValue("api_key")._tag) // "None" (because "secret123" is not a number)
|
|
182
|
+
|
|
183
|
+
// Example 13: flatZip for multi-step validation pipeline
|
|
184
|
+
interface UserData {
|
|
185
|
+
email: string
|
|
186
|
+
password: string
|
|
187
|
+
age: number
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const validateEmail = (email: string): Option<string> => {
|
|
191
|
+
return email.includes("@") ? Option.Some(email) : Option.None
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const validatePassword = (password: string): Option<string> => {
|
|
195
|
+
return password.length >= 8 ? Option.Some(password) : Option.None
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const validateAge = (age: number): Option<number> => {
|
|
199
|
+
return age >= 18 ? Option.Some(age) : Option.None
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const validateUserData = (data: UserData): Option<UserData> => {
|
|
203
|
+
return Option.Some(data)
|
|
204
|
+
.flatMap((data) => validateEmail(data.email).map(() => data))
|
|
205
|
+
.flatMap((data) => validatePassword(data.password).map(() => data))
|
|
206
|
+
.flatMap((data) => validateAge(data.age).map(() => data))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
console.log(
|
|
210
|
+
"13. Valid user:",
|
|
211
|
+
validateUserData({
|
|
212
|
+
email: "test@example.com",
|
|
213
|
+
password: "password123",
|
|
214
|
+
age: 25,
|
|
215
|
+
}).unwrap(),
|
|
216
|
+
) // { email: "test@example.com", password: "password123", age: 25 }
|
|
217
|
+
console.log(
|
|
218
|
+
" Invalid email:",
|
|
219
|
+
validateUserData({
|
|
220
|
+
email: "invalid",
|
|
221
|
+
password: "password123",
|
|
222
|
+
age: 25,
|
|
223
|
+
})._tag,
|
|
224
|
+
) // "None"
|
|
225
|
+
|
|
226
|
+
// Example 14: flatZip for safe nested access with context
|
|
227
|
+
type Department = { name: string; manager?: Employee }
|
|
228
|
+
type Employee = { name: string; department?: Department }
|
|
229
|
+
|
|
230
|
+
const getDepartmentManager = (dept: Department): Option<Employee> => {
|
|
231
|
+
return Option.fromNullable(dept.manager)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const getEmployeeDepartment = (emp: Employee): Option<Department> => {
|
|
235
|
+
return Option.fromNullable(emp.department)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const getManagerWithEmployee = (
|
|
239
|
+
emp: Employee,
|
|
240
|
+
): Option<[Employee, Employee]> => {
|
|
241
|
+
return Option.Some(emp).flatZip((emp) =>
|
|
242
|
+
getEmployeeDepartment(emp).flatMap((dept) => getDepartmentManager(dept)),
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const dept: Department = { name: "Engineering", manager: { name: "Alice" } }
|
|
247
|
+
const emp: Employee = { name: "Bob", department: dept }
|
|
248
|
+
|
|
249
|
+
console.log("14. Manager with employee:", getManagerWithEmployee(emp).unwrap()) // [emp, manager]
|
|
250
|
+
|
|
251
|
+
console.log("\n=== All flatZip examples completed ===")
|