@carbonteq/fp 0.8.2 → 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 (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +237 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
package/README.md CHANGED
@@ -22,26 +22,26 @@ yarn add @carbonteq/fp
22
22
  bun add @carbonteq/fp
23
23
  ```
24
24
 
25
- # But why fp?
25
+ ## But why fp?
26
26
 
27
27
  In JavaScript and TypeScript, dealing with `null`, `undefined`, and errors can lead to verbose, error-prone code. `fp` introduces functional paradigms that make handling these cases cleaner and more reliable. By leveraging `fp`, you can reduce boilerplate, improve readability, and create more maintainable applications.
28
28
 
29
29
  To demonstrate the utility of `fp`, let us consider a use case where we need to retrieve a user's email and address.
30
30
 
31
- ### Without using the `fp` library
31
+ ## Without using the `fp` library
32
32
 
33
33
  ```typescript
34
34
  function getUserByEmail(user: { email?: string }): string | null {
35
35
  return user.email ? user.email : null;
36
36
  }
37
37
 
38
- function getUserAdress(user: { email?: string }): string | null {
39
- return user.email ? "Some Address" : null;
38
+ function getUserAddress(email: string): string | null {
39
+ return email ? "Some Address" : null;
40
40
  }
41
41
 
42
42
  const email = getUserByEmail({ email: "test@test.com" });
43
43
  if (email) {
44
- const address = getUserAdress(email);
44
+ const address = getUserAddress(email);
45
45
  if (address) {
46
46
  console.log(`User ${email} has address: ${address}`);
47
47
  } else {
@@ -50,12 +50,12 @@ if (email) {
50
50
  } else {
51
51
  console.error("Email not found");
52
52
  }
53
- // Output: User test@test.com has address: Some Address
53
+ // Example output: User test@test.com has address: Some Address
54
54
  ```
55
55
 
56
56
  Now imagine if we had more complex use cases that involved more than two optional values. We would have to nest if statements and handle errors manually. This is where `fp` comes in.
57
57
 
58
- ### With using the `fp` library
58
+ ### Using the `fp` library
59
59
 
60
60
  ```typescript
61
61
  import { Option, matchOpt } from "@carbonteq/fp";
@@ -64,12 +64,12 @@ function getUserByEmail(user: { email?: string }): Option<string> {
64
64
  return user.email ? Option.Some(user.email) : Option.None;
65
65
  }
66
66
 
67
- function getUserAddress(user: { email?: string }): Option<string> {
68
- return user.email ? Option.Some("Some Address") : Option.None;
67
+ function getUserAddress(email: string): Option<string> {
68
+ return Option.Some("Some Address");
69
69
  }
70
70
 
71
71
  const res = getUserByEmail({ email: "test@test.com" }).flatZip((email) =>
72
- getUserAddress({ email }),
72
+ getUserAddress(email),
73
73
  );
74
74
 
75
75
  matchOpt(res, {
@@ -80,14 +80,19 @@ matchOpt(res, {
80
80
  console.error("User or Address not found");
81
81
  },
82
82
  });
83
- // Output: User test@test.com has address: Some Address
83
+ // Example output: User test@test.com has address: Some Address
84
84
  ```
85
85
 
86
- # Table of Contents
86
+ ## Table of Contents
87
87
 
88
+ - [Examples](#examples)
88
89
  - [Usage](#usage)
89
90
  - [The `Result` type](#the-result-type)
90
91
  - [The `Option` type](#the-option-type)
92
+ - [Fluent `match()` builder](#fluent-match-builder)
93
+ - [The `ExperimentalResult` type (Experimental)](#the-experimentalresult-type-experimental)
94
+ - [The `ExperimentalOption` type (Experimental)](#the-experimentaloption-type-experimental)
95
+ - [The `Flow` namespaces](#the-flow-namespaces)
91
96
  - [Cheatsheet](#cheatsheet)
92
97
  - [map](#map)
93
98
  - [flatMap](#flatmap)
@@ -95,21 +100,26 @@ matchOpt(res, {
95
100
  - [flatZip](#flatzip)
96
101
  - [Comparison of map and zip](#comparison-of-map-flatmap-zip-and-flatzip)
97
102
  - [Some Other Useful Functions](#some-other-useful-functions)
98
- - [mapErr](#maperr)
99
- - [mapOr](#mapor) <!-- - [tap](#tap) -->
100
- - [all](#all)
101
- - [validate](#validate)
102
- - [unwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
103
- - [safeUnwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
104
- - [unwrapOr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
105
- - [unwrapOrElse](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
106
- - [safeUnwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
107
- - [unwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
103
+ - [Creating Values from Existing Data](#creating-values-from-existing-data)
104
+ - [Exception Handling](#exception-handling)
105
+ - [Transforming Inner Values](#transforming-inner-values)
106
+ - [Combining & Converting](#combining--converting)
107
+ - [Error Recovery & Side Effects](#error-recovery--side-effects)
108
+ - [Aggregation Helpers](#aggregation-helpers)
108
109
  - [Build Your First Pipeline](#build-your-first-pipeline)
109
110
  - [Synchronous Pipeline](#synchronous-pipeline)
110
111
  - [Asynchronous Pipeline](#asynchronous-pipeline)
111
112
 
112
- # Usage
113
+ ## Examples
114
+
115
+ Examples are split between stable and experimental APIs.
116
+
117
+ - Stable runnable examples live under `examples/result/`, `examples/option/`, and `examples/flow/`.
118
+ - Experimental runnable examples live under `examples/result-experimental/`, `examples/option-experimental/`, and `examples/flow-experimental/`.
119
+
120
+ See `examples/README.md` for the runnable index and file paths.
121
+
122
+ ## Usage
113
123
 
114
124
  ## The `Result` type
115
125
 
@@ -122,6 +132,21 @@ const res1: Result<number, string> = Result.Ok(5); // Contains the value 5
122
132
  const res2: Result<number, string> = Result.Err("Some Error"); // Contains the error "Some Error"
123
133
  ```
124
134
 
135
+ Async variants
136
+
137
+ In the stable API, async mappers/binders are allowed on the same methods. The async work stays inside the Result, so the return type is `Result<Promise<T>, E>`. Use `toPromise()` when you need `Promise<Result<T, E>>`.
138
+
139
+ ```typescript
140
+ // Sync
141
+ Result.Ok(5).map((x) => x * 2); // Result<number, never>
142
+ Result.Ok(5).flatMap((x) => Result.Ok(x * 2));
143
+
144
+ // Async (stable)
145
+ const mapped = Result.Ok(5).map(async (x) => x * 2); // Result<Promise<number>, never>
146
+ const chained = Result.Ok(5).flatMap(async (x) => Result.Ok(x * 2)); // Result<Promise<number>, never>
147
+ const resolved = await chained.toPromise(); // Promise<Result<number, never>>
148
+ ```
149
+
125
150
  ## The `Option` type
126
151
 
127
152
  The `Option` type represents a value that might or might not be present. It eliminates the need for manual checks for `null` or `undefined`.
@@ -133,14 +158,127 @@ const opt1: Option<number> = Option.Some(5); // Contains the value 5
133
158
  const opt2: Option<number> = Option.None; // Contains no value (None)
134
159
  ```
135
160
 
161
+ Async variants
162
+
163
+ In the stable API, async mappers/predicates are allowed on the same methods. The async work stays inside the Option, so the return type is `Option<Promise<T>>`. Use `toPromise()` when you need `Promise<Option<T>>`.
164
+
165
+ ```typescript
166
+ // Sync
167
+ Option.Some(5).map((x) => x * 2); // Option<number>
168
+ Option.Some(5).flatMap((x) => Option.Some(x * 2));
169
+
170
+ // Async (stable)
171
+ const mapped = Option.Some(5).map(async (x) => x * 2); // Option<Promise<number>>
172
+ const chained = Option.Some(5).flatMap(async (x) => Option.Some(x * 2)); // Option<Promise<number>>
173
+ const filtered = Option.Some(5).filter(async (x) => x > 3); // Option<Promise<number>>
174
+ const resolved = await filtered.toPromise(); // Promise<Option<number>>
175
+ ```
176
+
177
+ ## Fluent `match()` builder
178
+
179
+ Use `match()` for fluent, exhaustive pattern matching across stable and experimental `Option`/`Result` values, plus generic discriminated unions.
180
+
181
+ ```typescript
182
+ import { match, P, Result } from "@carbonteq/fp";
183
+
184
+ const message = match(Result.Ok(42) as Result<number, string>)
185
+ .with(P.Ok(P.eq(42)), () => "exactly 42")
186
+ .with(P.Ok(P.not(P.oneOf(42, 43))), () => "ok but not 42 or 43")
187
+ .with(P.Ok(), (value) => `other ok: ${value}`)
188
+ .with(P.Err(), (error) => `error: ${error}`)
189
+ .exhaustive();
190
+
191
+ const branch = match(Result.Err("timeout") as Result<number, string>)
192
+ .when(P.IsOk, () => "ok")
193
+ .when(P.IsErr, () => "err")
194
+ .otherwise(() => "other");
195
+
196
+ const combined = match(Result.Ok(42) as Result<number, string>)
197
+ .with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
198
+ .with(P.Ok(), () => "miss")
199
+ .with(P.Err(), () => "err")
200
+ .exhaustive();
201
+ ```
202
+
203
+ `match()` is intentionally synchronous. If you have async-inner stable values, settle first:
204
+
205
+ ```typescript
206
+ import { match, Result } from "@carbonteq/fp";
207
+
208
+ const asyncResult = Result.Ok(Promise.resolve(10)); // Result<Promise<number>, never>
209
+ const settled = await asyncResult.toPromise(); // Promise<Result<number, never>>
210
+
211
+ const label = match(settled)
212
+ .with("Ok", (value) => `value=${value}`)
213
+ .with("Err", () => "error")
214
+ .exhaustive();
215
+ ```
216
+
217
+ ---
218
+
219
+ ## The `ExperimentalResult` type (Experimental)
220
+
221
+ `ExperimentalResult` differs from the stable `Result` by providing explicit async methods like `mapAsync` and `flatMapAsync` that return `Promise<ExperimentalResult<T, E>>` directly, rather than returning `Result<Promise<T>, E>` and requiring `toPromise()`. It also includes generator-based APIs (`gen`, `asyncGen`, and adapter variants) used by `Flow`.
222
+
223
+ ```typescript
224
+ import { ExperimentalResult } from "@carbonteq/fp";
225
+ ```
226
+
227
+ ## The `ExperimentalOption` type (Experimental)
228
+
229
+ `ExperimentalOption` mirrors the stable `Option` API but provides explicit async methods like `mapAsync`, `flatMapAsync`, and `filterAsync` that return `Promise<ExperimentalOption<T>>` rather than `Option<Promise<T>>`. It also includes generator-based APIs (`gen`, `asyncGen`, and adapter variants) and is the `Option` type used by `Flow`.
230
+
231
+ ```typescript
232
+ import { ExperimentalOption } from "@carbonteq/fp";
233
+ ```
234
+
235
+ ---
236
+
237
+ ## The `Flow` namespaces
238
+
239
+ `Flow` is the stable generator namespace and works with stable `Option` + `Result`, returning stable `Result`.
240
+
241
+ ```typescript
242
+ import { Flow, Option, Result, UnwrappedNone } from "@carbonteq/fp";
243
+
244
+ const result = Flow.gen(function* () {
245
+ const a = yield* Option.Some(5);
246
+ const b = yield* Result.Ok(10);
247
+ const c = yield* Option.fromNullable(20);
248
+ return a + b + c;
249
+ });
250
+
251
+ // Result<number, UnwrappedNone>
252
+ ```
253
+
254
+ `ExperimentalFlow` is the experimental counterpart and works with `ExperimentalOption` + `ExperimentalResult`, returning `ExperimentalResult`.
255
+
256
+ ```typescript
257
+ import {
258
+ ExperimentalFlow,
259
+ ExperimentalOption,
260
+ ExperimentalResult,
261
+ } from "@carbonteq/fp";
262
+
263
+ const result = ExperimentalFlow.gen(function* () {
264
+ const a = yield* ExperimentalOption.Some(5);
265
+ const b = yield* ExperimentalResult.Ok(10);
266
+ return a + b;
267
+ });
268
+ ```
269
+
270
+ Both namespaces provide `gen`, `genAdapter`, `asyncGen`, and `asyncGenAdapter`.
271
+
136
272
  ---
137
273
 
138
274
  ## Cheatsheet
139
275
 
140
- #### `map`
276
+ ### `map`
141
277
 
142
278
  Transforms the `Some` or `Ok` value inside `Option` or `Result`.
143
279
 
280
+ If your mapper is async, `map` returns `Option<Promise<U>>` or `Result<Promise<U>, E>`. Use `toPromise()` when you need a resolved `Option`/`Result`.
281
+
144
282
  Let's say we want to apply a 10% bonus to the account balance of a user.
145
283
 
146
284
  ```typescript
@@ -163,7 +301,7 @@ async function applyBonus() {
163
301
  return balanceOption;
164
302
  }
165
303
 
166
- console.log(await applyBonus()); // Output: Some(110)
304
+ console.log(await applyBonus()); // Example output: Some(110)
167
305
  ```
168
306
 
169
307
  #### `flatMap`
@@ -210,14 +348,14 @@ const processUser = async (
210
348
  return validationResult;
211
349
  };
212
350
 
213
- console.log(await processUser("Alice", 30)); // Output: Result.Ok("User Alice saved successfully!")
351
+ console.log(await processUser("Alice", 30)); // Example output: Result.Ok("User Alice saved successfully!")
214
352
 
215
353
  /* validationResult is of type Result<string, Error> instead of Result<Result<string, Error>, Error> (which is what would have happened if we used map instead of flatMap) */
216
354
  ```
217
355
 
218
356
  #### `zip`
219
357
 
220
- Creates a tuple `[T, U]` where the second value `U` is _derived_ from the first value `T` using a function `f`.
358
+ Creates a tuple `[T, U]` where the second value `U` is *derived* from the first value `T` using a function `f`.
221
359
  For example, suppose we want to pair the product's original price `T` and discounted price `U`.
222
360
 
223
361
  ```typescript
@@ -241,14 +379,14 @@ async function applyDiscount(
241
379
  return originalPrice; //originalPrice is of type Result<[number, number], Error>
242
380
  }
243
381
 
244
- console.log(await applyDiscount("123")); // Output: Result.Ok([100, 90])
382
+ console.log(await applyDiscount("123")); // Example output: Result.Ok([100, 90])
245
383
  ```
246
384
 
247
385
  Here `derivedPair` is a `Result<[number, number], Error>`. Note that `T` = `100` and `U` = `90`.
248
386
 
249
387
  #### `flatZip`
250
388
 
251
- Combines the current `Result<T, E>` with another `Result<U, E2>`, or the current `Option<T>` with another `Option<U>`. Unlike zip, which pairs a value with a derived one, flatZip works with **two independent Result/Option values** and combines their contents into a tuple `[T, U]`. It ensures the Result/Option values are Ok/Some to proceed; otherwise, it propagates the first encountered Err/None.
389
+ Combines the current `Result<T, E>` with a **dependent** `Result<U, E2>` produced from `T`, or the current `Option<T>` with a dependent `Option<U>` produced from `T`. Unlike `zip`, which pairs a value with a plain derived value, `flatZip` expects the callback to return a `Result`/`Option` and then flattens the outcome into `[T, U]`. It proceeds only when both steps are `Ok`/`Some`; otherwise, it propagates the first `Err`/`None`.
252
390
 
253
391
  Lets say we want to combine the product price and product stock into a tuple `[number, number]`.
254
392
 
@@ -262,10 +400,10 @@ async function fetchProductPrice(productId: string): Promise<Option<number>> {
262
400
  return Option.Some(100);
263
401
  }
264
402
 
265
- // Simulated function to fetch product stock
266
- async function fetchProductStock(productId: string): Promise<Option<number>> {
267
- // Simulate fetching stock from a database
268
- await Promise.resolve(productId);
403
+ // Simulated function to fetch product stock (receives price, returns Option)
404
+ async function fetchProductStock(price: number): Promise<Option<number>> {
405
+ // Simulate fetching stock from a database based on price
406
+ await Promise.resolve(price);
269
407
  return Option.Some(50);
270
408
  }
271
409
 
@@ -280,18 +418,18 @@ async function fetchProductDetails(
280
418
  return productDetails; // Option<[number, number]>
281
419
  }
282
420
 
283
- console.log(await fetchProductDetails("123")); // Output: Option.Some([100, 50])
421
+ console.log(await fetchProductDetails("123")); // Example output: Option.Some([100, 50])
284
422
  ```
285
423
 
286
424
  ## Comparison of `map`, `flatMap`, `zip`, and `flatZip`
287
425
 
288
426
  | **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** |
289
427
  | --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
290
- | **Purpose** | Transforms the value inside an `Ok` or `Some`. | Chains dependent computations where each computation returns a `Result` or `Option`. | Combines the current value with another derived value into a tuple `[T, U]`. | Combines two independent `Result` or `Option` values into a tuple `[T, U]`. |
428
+ | **Purpose** | Transforms the value inside an `Ok` or `Some`. | Chains dependent computations where each computation returns a `Result` or `Option`. | Combines the current value with another derived value into a tuple `[T, U]`. | Chains a dependent computation returning `Result`/`Option` and combines both values into `[T, U]`. |
291
429
  | **Input** | A function `(val: T) => U`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` to transform the current value into another `Result` or `Option`. | A function `(val: T) => U` to derive a new value `U` from the current value `T`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` that returns another `Result` or `Option`. |
292
430
  | **Output** | `Result<U, E>`, `Option<U>` | `Result<U, E>`, `Option<U>` | `Result<[T, U], E>`, `Option<[T, U]>` | `Result<[T, U], E>`, `Option<[T, U]>`. |
293
431
  | **Error Propagation** | Propagates `Err`/`None` if the `Result`/`Option` is `Err`/`None`. | Propagates the first `Err`/`None` encountered in the chain. | Propagates `Err`/`None` if the current `Result`/`Option` or derived value is `Err`/`None`. | Propagates the first `Err`/`None` encountered between the two `Result`/`Option` values. |
294
- | **Use Case** | When you want to transform a value inside `Ok`/`Some`. | When the next computation depends on the current value and returns a `Result`/`Option`. | When you want to pair the current value with a derived one. | When you want to combine two independent `Result`/`Option` values into a tuple. |
432
+ | **Use Case** | When you want to transform a value inside `Ok`/`Some`. | When the next computation depends on the current value and returns a `Result`/`Option`. | When you want to pair the current value with a derived one. | When you want to pair the current value with a dependent `Result`/`Option` computation. |
295
433
 
296
434
  ---
297
435
 
@@ -342,54 +480,17 @@ async function findUserById(id: number): Promise<Option<number>> {
342
480
  return Option.Some(id);
343
481
  }
344
482
 
345
- // A safe function that returns a string error message if the user is not found, instead of throwing an exception
346
- async function safeFindUserById(id: number): Promise<Option<string>> {
347
- const res = (await findUserById(id)).mapOr(
348
- `User not found`,
349
- (res) => `User: ${res}`,
350
- );
351
- return res;
483
+ // A safe function that returns a string message (not an Option) - mapOr returns the value directly
484
+ async function safeFindUserById(id: number): Promise<string> {
485
+ const userOpt = await findUserById(id);
486
+ return userOpt.mapOr(`User not found`, (res) => `User: ${res}`);
352
487
  }
353
488
 
354
489
  // Example usage
355
- console.log(await safeFindUserById(10)); // Some(User: 10)
356
- console.log(await safeFindUserById(0)); // Some(User not found)
490
+ console.log(await safeFindUserById(10)); // User: 10
491
+ console.log(await safeFindUserById(0)); // User not found
357
492
  ```
358
493
 
359
- <!-- #### `tap`
360
-
361
- `tap` is used to perform side effects on the `Result`/`Option` value without altering its contents. It is useful for logging, auditing, debugging complex chains of operations etc.
362
-
363
- ```typescript
364
- import { Result } from "@carbonteq/fp";
365
-
366
- // Simulated database functions
367
- async function findUserById(userId: number): Promise<Result<Record<string, number>, string>> {
368
- // Simulate a database lookup
369
- await Promise.resolve(userId);
370
- if (userId === 0) {
371
- return Result.Err("User not found");
372
- }
373
- return Result.Ok({ id: userId, balance: 100 });
374
- }
375
-
376
- function updateBalance(user: Record<string, number>, amount: number): Result<Record<string, number>, string> {
377
- if (user.balance < amount) {
378
- return Result.Err("Insufficient funds");
379
- }
380
- return Result.Ok({ ...user, balance: user.balance - amount });
381
- }
382
-
383
- // Process withdrawal with logging
384
- const res = (await findUserById(1))
385
- .tap((user) => console.log(`[Audit] User found: ${user.id}`))
386
- .flatMap((user) => updateBalance(user, 10))
387
- .tap((updated) => console.log(`[Transaction] New balance: $${updated.balance}`))
388
- .mapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
389
-
390
- console.log(res); // Result.Ok({ id: 1, balance: 90 })
391
- ``` -->
392
-
393
494
  #### `all`
394
495
 
395
496
  `all` is used to combine an array of Results. If any errors exist they are accumulated, else the values are accumulated.
@@ -421,6 +522,7 @@ type Like = {
421
522
  type Reply = {
422
523
  replyId: string;
423
524
  postId: Post["postId"];
525
+ data: string;
424
526
  createdAt: Date | string;
425
527
  author: User["userId"];
426
528
  };
@@ -485,11 +587,11 @@ async function getUserData(userId: string) {
485
587
  const hash = userIdRes.flatMap(generateHash);
486
588
 
487
589
  const userData = await Result.all(
488
- user, // Result<Promise<T>, E>
489
- posts, // Result<Promise<T>, E>
490
- likes, // Result<Promise<T>, E>
491
- replies, // Result<Promise<T>, E>
492
- hash, // Result<T, E>
590
+ user,
591
+ posts,
592
+ likes,
593
+ replies,
594
+ hash,
493
595
  ).toPromise();
494
596
 
495
597
  matchRes(userData, {
@@ -585,9 +687,10 @@ const validatedOk = Result.Ok("password321!").validate([
585
687
  ]);
586
688
  console.log(validatedOk.unwrap()); // password321!
587
689
 
588
- const validatedErr = await Result.Ok("pword")
589
- .validate([hasMinimumLength, hasSpecialCharacters])
590
- .toPromise();
690
+ const validatedErr = Result.Ok("pword").validate([
691
+ hasMinimumLength,
692
+ hasSpecialCharacters,
693
+ ]);
591
694
  console.log(validatedErr.unwrapErr()); // [Error: Password must be at least 8 characters, Error: Password must contain at least one special character]
592
695
 
593
696
  const validatedErrs = await Result.Ok("password123!")
@@ -596,7 +699,7 @@ const validatedErrs = await Result.Ok("password123!")
596
699
  console.log(validatedErrs.unwrapErr()); // [Error: New password cannot be the same as previous password]
597
700
  ```
598
701
 
599
- #### `unwrap`, `safeUnwrapErr`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
702
+ #### `unwrap`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
600
703
 
601
704
  These functions are used to extract the value from a `Result`. Note that **only `unwrap` and `safeUnwrap` are available for `Option`**.
602
705
 
@@ -621,11 +724,533 @@ const errorResult = Result.Err(new Error("Something went wrong"));
621
724
  console.log(errorResult.unwrapErr()); // unwrapErr: Error: Something went wrong (Extracts the error from Result.Err, throwing an error if it's Ok)
622
725
  ```
623
726
 
727
+ ---
728
+
729
+ ### Creating Values from Existing Data
730
+
731
+ #### `Option.fromNullable`
732
+
733
+ Creates an `Option` from a value that might be `null` or `undefined`, returning `None` for those values.
734
+
735
+ ```typescript
736
+ import { Option } from "@carbonteq/fp";
737
+
738
+ function findUser(id: string): { name: string } | null {
739
+ return id === "1" ? { name: "Alice" } : null;
740
+ }
741
+
742
+ const user = Option.fromNullable(findUser("1"));
743
+ console.log(user); // Some({ name: "Alice" })
744
+
745
+ const missing = Option.fromNullable(findUser("999"));
746
+ console.log(missing); // None
747
+ ```
748
+
749
+ #### `Option.fromFalsy`
750
+
751
+ Creates an `Option` from a value, returning `None` for any falsy value (`false`, `0`, `""`, `null`, `undefined`).
752
+
753
+ ```typescript
754
+ import { Option } from "@carbonteq/fp";
755
+
756
+ const valid = Option.fromFalsy("hello");
757
+ console.log(valid); // Some("hello")
758
+
759
+ const empty = Option.fromFalsy("");
760
+ console.log(empty); // None
761
+
762
+ const zero = Option.fromFalsy(0);
763
+ console.log(zero); // None
764
+ ```
765
+
766
+ #### `Option.fromPredicate`
767
+
768
+ Creates an `Option` based on a predicate function - returns `Some` if the predicate returns `true`, else `None`.
769
+
770
+ ```typescript
771
+ import { Option } from "@carbonteq/fp";
772
+
773
+ const age = 25;
774
+ const adult = Option.fromPredicate(age, (a) => a >= 18);
775
+ console.log(adult); // Some(25)
776
+
777
+ const minor = Option.fromPredicate(15, (a) => a >= 18);
778
+ console.log(minor); // None
779
+ ```
780
+
781
+ #### `Result.fromNullable`
782
+
783
+ Creates a `Result` from a nullable value, returning `Err` with the provided error for `null` or `undefined`.
784
+
785
+ ```typescript
786
+ import { Result } from "@carbonteq/fp";
787
+
788
+ function getConfig(key: string): string | undefined {
789
+ return process.env[key];
790
+ }
791
+
792
+ const config = Result.fromNullable(getConfig("API_KEY"), "API_KEY not set");
793
+ console.log(config); // Ok("...") or Err("API_KEY not set")
794
+ ```
795
+
796
+ #### `Result.fromPredicate`
797
+
798
+ Creates a `Result` based on a predicate function - returns `Ok` with the value if the predicate returns `true`, else `Err` with the provided error.
799
+
800
+ ```typescript
801
+ import { Result } from "@carbonteq/fp";
802
+
803
+ const score = 85;
804
+ const passed = Result.fromPredicate(score, (s) => s >= 60, "Score too low");
805
+ console.log(passed); // Ok(85)
806
+
807
+ const failed = Result.fromPredicate(45, (s) => s >= 60, "Score too low");
808
+ console.log(failed); // Err("Score too low")
809
+ ```
810
+
811
+ ---
812
+
813
+ ### Exception Handling
814
+
815
+ #### `Result.tryCatch`
816
+
817
+ Wraps a synchronous operation in a `Result`, catching any exceptions and converting them to `Err`.
818
+
819
+ ```typescript
820
+ import { Result } from "@carbonteq/fp";
821
+
822
+ function parseJson(json: string): Result<unknown, Error> {
823
+ return Result.tryCatch(
824
+ () => JSON.parse(json),
825
+ (e) => (e instanceof Error ? e : new Error(String(e))),
826
+ );
827
+ }
828
+
829
+ console.log(parseJson('{"name":"Alice"}')); // Ok({ name: "Alice" })
830
+ console.log(parseJson("invalid json")); // Err(SyntaxError: ...)
831
+ ```
832
+
833
+ #### `Result.tryAsyncCatch`
834
+
835
+ Wraps an asynchronous operation in a `Result`, catching any exceptions and converting them to `Err`.
836
+
837
+ ```typescript
838
+ import { Result } from "@carbonteq/fp";
839
+
840
+ async function fetchUserData(
841
+ id: string,
842
+ ): Promise<Result<{ name: string }, Error>> {
843
+ return Result.tryAsyncCatch(
844
+ async () => {
845
+ const response = await fetch(`/api/users/${id}`);
846
+ return response.json();
847
+ },
848
+ (e) => (e instanceof Error ? e : new Error(String(e))),
849
+ );
850
+ }
851
+
852
+ const user = await fetchUserData("123");
853
+ console.log(user); // Ok({ name: "..." }) or Err(Error: ...)
854
+ ```
855
+
856
+ ---
857
+
858
+ ### Transforming Inner Values
859
+
860
+ #### `Option.filter`
861
+
862
+ Filters the value inside an `Option` based on a predicate, returning `None` if the predicate returns `false`.
863
+
864
+ ```typescript
865
+ import { Option } from "@carbonteq/fp";
866
+
867
+ const age = Option.Some(25);
868
+ const adult = age.filter((a) => a >= 18);
869
+ console.log(adult); // Some(25)
870
+
871
+ const minor = Option.Some(15).filter((a) => a >= 18);
872
+ console.log(minor); // None
873
+ ```
874
+
875
+ #### `Option.innerMap`
876
+
877
+ Transforms array elements inside an `Option<Array<T>>`.
878
+
879
+ ```typescript
880
+ import { Option } from "@carbonteq/fp";
881
+
882
+ const numbers = Option.Some([1, 2, 3, 4, 5]);
883
+ const doubled = numbers.innerMap((n) => n * 2);
884
+ console.log(doubled); // Some([2, 4, 6, 8, 10])
885
+ ```
886
+
887
+ #### `Result.innerMap`
888
+
889
+ Transforms array elements inside a `Result<Array<T>, E>`.
890
+
891
+ ```typescript
892
+ import { Result } from "@carbonteq/fp";
893
+
894
+ const numbers = Result.Ok([1, 2, 3, 4, 5]);
895
+ const squared = numbers.innerMap((n) => n * n);
896
+ console.log(squared); // Ok([1, 4, 9, 16, 25])
897
+ ```
898
+
899
+ #### `Result.mapBoth`
900
+
901
+ Transforms both the success value and the error value simultaneously.
902
+
903
+ ```typescript
904
+ import { Result } from "@carbonteq/fp";
905
+
906
+ const result = Result.Ok(42);
907
+ const decorated = result.mapBoth(
908
+ (val) => `Success: ${val}`,
909
+ (err) => `Error: ${err}`,
910
+ );
911
+ console.log(decorated); // Ok("Success: 42")
912
+
913
+ const error = Result.Err("Something failed");
914
+ const decoratedError = error.mapBoth(
915
+ (val) => `Success: ${val}`,
916
+ (err) => `Error: ${err}`,
917
+ );
918
+ console.log(decoratedError); // Err("Error: Something failed")
919
+ ```
920
+
921
+ ---
922
+
923
+ ### Combining & Converting
924
+
925
+ #### `Option.toResult`
926
+
927
+ Converts an `Option` to a `Result`, using the provided error for `None`.
928
+
929
+ ```typescript
930
+ import { Option } from "@carbonteq/fp";
931
+
932
+ const user = Option.Some({ name: "Alice" });
933
+ const userResult = user.toResult("User not found");
934
+ console.log(userResult); // Ok({ name: "Alice" })
935
+
936
+ const missing = Option.None.toResult("User not found");
937
+ console.log(missing); // Err("User not found")
938
+ ```
939
+
940
+ #### `Result.toOption`
941
+
942
+ Converts a `Result` to an `Option`, discarding error information.
943
+
944
+ ```typescript
945
+ import { Result } from "@carbonteq/fp";
946
+
947
+ const success = Result.Ok(42);
948
+ const opt = success.toOption();
949
+ console.log(opt); // Some(42)
950
+
951
+ const failure = Result.Err("Failed");
952
+ const optFromErr = failure.toOption();
953
+ console.log(optFromErr); // None
954
+ ```
955
+
956
+ #### `Result.zipErr`
957
+
958
+ Runs a validation/binding function on the Ok value that can produce a new error, while preserving the original Ok value. If the function returns an `Err`, that error is returned. If the initial result is already `Err`, it short-circuits and returns that error.
959
+
960
+ ```typescript
961
+ import { Result } from "@carbonteq/fp";
962
+
963
+ const checkPermissions = (userId: string) =>
964
+ Result.Ok(userId).zipErr((id) =>
965
+ id === "guest"
966
+ ? Result.Err("Guest users have limited access")
967
+ : Result.Ok(undefined),
968
+ );
969
+
970
+ const admin = checkPermissions("admin-123");
971
+ console.log(admin); // Ok("admin-123")
972
+
973
+ const guest = checkPermissions("guest");
974
+ console.log(guest); // Err("Guest users have limited access")
975
+
976
+ const okNoChange = Result.Ok("42").zipErr((id) => Result.Ok(id.length));
977
+ console.log(okNoChange); // Ok("42")
978
+
979
+ const alreadyFailed = Result.Err<string, string>("Network error").zipErr(() =>
980
+ Result.Err("Validation error"),
981
+ );
982
+ console.log(alreadyFailed); // Err("Network error") - short-circuits
983
+ ```
984
+
985
+ ##### `mapErr` vs `zipErr`
986
+
987
+ `mapErr` transforms the error value only; it never runs on `Ok`. `zipErr` runs a binder on the `Ok` value that can *introduce* a new error, while preserving the original `Ok` value on success.
988
+
989
+ ```typescript
990
+ import { Result } from "@carbonteq/fp";
991
+
992
+ const res = Result.Err<Error, number>(new Error("boom")).mapErr(
993
+ (e) => e.message,
994
+ );
995
+ console.log(res); // Err("boom")
996
+
997
+ const ok = Result.Ok("42").zipErr((value) =>
998
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
999
+ );
1000
+ console.log(ok); // Ok("42")
1001
+
1002
+ const err = Result.Ok("0").zipErr((value) =>
1003
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
1004
+ );
1005
+ console.log(err); // Err("invalid")
1006
+ ```
1007
+
1008
+ #### `Result.flip`
1009
+
1010
+ Swaps the `Ok` and `Err` states, turning success into failure and vice versa.
1011
+
1012
+ ```typescript
1013
+ import { Result } from "@carbonteq/fp";
1014
+
1015
+ const success = Result.Ok("Success value");
1016
+ const flipped = success.flip();
1017
+ console.log(flipped); // Err("Success value")
1018
+
1019
+ const failure = Result.Err("Error value");
1020
+ const flippedError = failure.flip();
1021
+ console.log(flippedError); // Ok("Error value")
1022
+ ```
1023
+
1024
+ ---
1025
+
1026
+ ### Error Recovery & Side Effects
1027
+
1028
+ #### `tap`
1029
+
1030
+ Executes a side effect function for `Some` or `Ok` values, then returns the original `Option` or `Result`. Useful for logging, debugging, or executing effects without changing the value.
1031
+
1032
+ ```typescript
1033
+ import { Result } from "@carbonteq/fp";
1034
+
1035
+ // Simulated database functions
1036
+ async function findUserById(
1037
+ userId: number,
1038
+ ): Promise<Result<Record<string, number>, string>> {
1039
+ // Simulate a database lookup
1040
+ await Promise.resolve(userId);
1041
+ if (userId === 0) {
1042
+ return Result.Err("User not found");
1043
+ }
1044
+ return Result.Ok({ id: userId, balance: 100 });
1045
+ }
1046
+
1047
+ function updateBalance(
1048
+ user: Record<string, number>,
1049
+ amount: number,
1050
+ ): Result<Record<string, number>, string> {
1051
+ if (user.balance < amount) {
1052
+ return Result.Err("Insufficient funds");
1053
+ }
1054
+ return Result.Ok({ ...user, balance: user.balance - amount });
1055
+ }
1056
+
1057
+ // Process withdrawal with logging
1058
+ const res = (await findUserById(1))
1059
+ .tap((user) => console.log(`[Audit] User found: ${user.id}`))
1060
+ .flatMap((user) => updateBalance(user, 10))
1061
+ .tap((updated) =>
1062
+ console.log(`[Transaction] New balance: $${updated.balance}`),
1063
+ )
1064
+ .tapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
1065
+
1066
+ console.log(res); // Result.Ok({ id: 1, balance: 90 })
1067
+ ```
1068
+
1069
+ #### `Result.tapErr`
1070
+
1071
+ Executes a side effect function for `Err` values, then returns the original `Result`.
1072
+
1073
+ ```typescript
1074
+ import { Result } from "@carbonteq/fp";
1075
+
1076
+ const result = Result.Err("Connection failed");
1077
+ const logged = result.tapErr((err) => {
1078
+ console.error(`[Error Log] ${new Date().toISOString()}: ${err}`);
1079
+ });
1080
+ console.log(logged); // Err("Connection failed")
1081
+ // Example output: [Error Log] 2025-01-07T...: Connection failed
1082
+ ```
1083
+
1084
+ #### `Result.orElse`
1085
+
1086
+ Recovers from an error by providing a fallback `Result`. If the current result is `Err`, the function is called with the error to produce a new result.
1087
+
1088
+ ```typescript
1089
+ import { Result } from "@carbonteq/fp";
1090
+
1091
+ function fetchFromCache(id: string): Result<string, Error> {
1092
+ return id === "cached"
1093
+ ? Result.Ok("Cached data")
1094
+ : Result.Err(new Error("Not in cache"));
1095
+ }
1096
+
1097
+ function fetchFromAPI(id: string): Result<string, Error> {
1098
+ return id === "1"
1099
+ ? Result.Ok("API data")
1100
+ : Result.Err(new Error("Not found"));
1101
+ }
1102
+
1103
+ const cached = fetchFromCache("cached").orElse((err) => fetchFromAPI("1"));
1104
+ console.log(cached); // Ok("Cached data")
1105
+
1106
+ const fromAPI = fetchFromCache("123").orElse((err) => fetchFromAPI("1"));
1107
+ console.log(fromAPI); // Ok("API data")
1108
+
1109
+ const failed = fetchFromCache("123").orElse((err) => fetchFromAPI("999"));
1110
+ console.log(failed); // Err(Error: Not found)
1111
+ ```
1112
+
1113
+ ---
1114
+
1115
+ ### Aggregation Helpers
1116
+
1117
+ #### `Option.any`
1118
+
1119
+ Returns the first `Some` from a list of `Option`s, or `None` if all are `None`.
1120
+
1121
+ ```typescript
1122
+ import { Option } from "@carbonteq/fp";
1123
+
1124
+ const first = Option.any(
1125
+ Option.None,
1126
+ Option.Some("First value"),
1127
+ Option.Some("Second value"),
1128
+ );
1129
+ console.log(first); // Some("First value")
1130
+
1131
+ const allNone = Option.any(Option.None, Option.None, Option.None);
1132
+ console.log(allNone); // None
1133
+ ```
1134
+
1135
+ #### `ExperimentalOption.gen`, `genAdapter`, `asyncGen`, `asyncGenAdapter`
1136
+
1137
+ Experimental generator-based methods for chaining Option operations with imperative-style syntax.
1138
+
1139
+ ```typescript
1140
+ import { ExperimentalOption as Option } from "@carbonteq/fp";
1141
+
1142
+ // Option.gen - simple sync chains (no adapter needed)
1143
+ const syncResult = Option.gen(function* () {
1144
+ const a = yield* Option.Some(1);
1145
+ const b = yield* Option.Some(2);
1146
+ return a + b;
1147
+ });
1148
+ console.log(syncResult); // Some(3)
1149
+
1150
+ // Option.asyncGen - async chains with explicit await
1151
+ const asyncResult = await Option.asyncGen(async function* () {
1152
+ const id = yield* Option.Some(1);
1153
+ const data = yield* await fetchUserData(id); // await Promise<Option> first
1154
+ const validated = yield* validate(data);
1155
+ return validated;
1156
+ });
1157
+
1158
+ // Option.genAdapter - better type inference for complex sync chains
1159
+ const complexSync = Option.genAdapter(function* ($) {
1160
+ const user = yield* $(fetchUser(123)); // sync Option
1161
+ const profile = yield* $(user.profile); // sync Option
1162
+ const valid = yield* $(validate(profile)); // sync Option
1163
+ return valid;
1164
+ });
1165
+
1166
+ // Option.asyncGenAdapter - cleaner async with auto-await handling
1167
+ const complexAsync = await Option.asyncGenAdapter(async function* ($) {
1168
+ const user = yield* $(fetchUser(123)); // sync or async Option
1169
+ const orders = yield* $(fetchOrders(user)); // Promise<Option> - auto-awaited
1170
+ const total = yield* $(calculateTotal(orders));
1171
+ return total;
1172
+ });
1173
+ ```
1174
+
1175
+ **Key differences:**
1176
+
1177
+ - `gen` / `asyncGen`: Simple, direct `yield*` with Option values
1178
+ - `genAdapter` / `asyncGenAdapter`: Uses `$()` adapter for better type inference and cleaner syntax
1179
+
1180
+ #### `Result.any`
1181
+
1182
+ Returns the first `Ok` from a list of `Result`s, or collects all errors if all are `Err`.
1183
+
1184
+ ```typescript
1185
+ import { Result } from "@carbonteq/fp";
1186
+
1187
+ const firstSuccess = Result.any(
1188
+ Result.Err("Error 1"),
1189
+ Result.Ok("First success"),
1190
+ Result.Ok("Second success"),
1191
+ );
1192
+ console.log(firstSuccess); // Ok("First success")
1193
+
1194
+ const allErrors = Result.any(
1195
+ Result.Err("Error 1"),
1196
+ Result.Err("Error 2"),
1197
+ Result.Err("Error 3"),
1198
+ );
1199
+ console.log(allErrors); // Err(["Error 1", "Error 2", "Error 3"])
1200
+ ```
1201
+
1202
+ #### `ExperimentalResult.gen`, `genAdapter`, `asyncGen`, `asyncGenAdapter`
1203
+
1204
+ Experimental generator-based methods for chaining Result operations with imperative-style syntax.
1205
+
1206
+ ```typescript
1207
+ import { ExperimentalResult as Result } from "@carbonteq/fp";
1208
+
1209
+ // Result.gen - simple sync chains (no adapter needed)
1210
+ const syncResult = Result.gen(function* () {
1211
+ const a = yield* Result.Ok(1);
1212
+ const b = yield* Result.Ok(2);
1213
+ return a + b;
1214
+ });
1215
+ console.log(syncResult); // Ok(3)
1216
+
1217
+ // Result.asyncGen - async chains with explicit await
1218
+ const asyncResult = await Result.asyncGen(async function* () {
1219
+ const id = yield* Result.Ok(1);
1220
+ const data = yield* await fetchUserData(id); // await Promise<Result> first
1221
+ const validated = yield* validate(data);
1222
+ return validated;
1223
+ });
1224
+
1225
+ // Result.genAdapter - better type inference for complex sync chains
1226
+ const complexSync = Result.genAdapter(function* ($) {
1227
+ const user = yield* $(fetchUser(123)); // sync Result
1228
+ const profile = yield* $(user.profile); // sync Result
1229
+ const valid = yield* $(validate(profile)); // sync Result
1230
+ return valid;
1231
+ });
1232
+
1233
+ // Result.asyncGenAdapter - cleaner async with auto-await handling
1234
+ const complexAsync = await Result.asyncGenAdapter(async function* ($) {
1235
+ const user = yield* $(fetchUser(123)); // sync or async Result
1236
+ const orders = yield* $(fetchOrders(user)); // Promise<Result> - auto-awaited
1237
+ const total = yield* $(calculateTotal(orders));
1238
+ return total;
1239
+ });
1240
+ ```
1241
+
1242
+ **Key differences:**
1243
+
1244
+ - `gen` / `asyncGen`: Simple, direct `yield*` with Result values
1245
+ - `genAdapter` / `asyncGenAdapter`: Uses `$()` adapter for better type inference and cleaner syntax
1246
+
1247
+ ---
1248
+
624
1249
  ## Build Your First Pipeline
625
1250
 
626
1251
  Let's build a pipeline for processing an e-commerce order. This example demonstrates handling user input validation, inventory checks, and order processing.
627
1252
 
628
- #### Synchronous Pipeline
1253
+ ### Synchronous Pipeline
629
1254
 
630
1255
  ```typescript
631
1256
  import { Result, matchRes } from "@carbonteq/fp";
@@ -699,7 +1324,7 @@ matchRes(result, {
699
1324
  },
700
1325
  });
701
1326
 
702
- // Output:
1327
+ // Example output:
703
1328
  // Order confirmed! Order ID: ORD-1716888600000
704
1329
  // Total: $59.98
705
1330
  // Order: {"productId":"PROD-123","quantity":2,"userId":"USER-456"}
@@ -710,8 +1335,7 @@ matchRes(result, {
710
1335
  Let's build an asynchronous pipeline for a user registration system that includes credentials verification and profile setup.
711
1336
 
712
1337
  ```typescript
713
- import { matchRes } from "@/match.js";
714
- import { Result } from "@/result.js";
1338
+ import { matchRes, Result } from "@carbonteq/fp";
715
1339
 
716
1340
  interface UserInput {
717
1341
  email: string;
@@ -776,13 +1400,12 @@ async function sendVerificationEmail(
776
1400
  return Result.Ok(profile);
777
1401
  }
778
1402
 
779
- // Main registration pipeline
1403
+ // Main registration pipeline using validate + flatMap
780
1404
  async function registerUser(
781
1405
  input: UserInput,
782
1406
  ): Promise<Result<UserProfile, string | string[]>> {
783
1407
  const res = await Result.Ok(input)
784
1408
  .validate([
785
- // handles both sync and async functions
786
1409
  ({ email }) => guardEmail(email),
787
1410
  ({ email }) => guardEmailAvailability(email),
788
1411
  ({ password }) => guardPassword(password),
@@ -818,7 +1441,7 @@ async function main() {
818
1441
  }
819
1442
 
820
1443
  main();
821
- // Output:
1444
+ // Example output:
822
1445
  // Verification email sent to newuser@example.com
823
1446
  // Email: newuser@example.com
824
1447
  // Registration successful!