@carbonteq/fp 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +310 -96
  2. package/dist/errors.cjs +1 -0
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.cts.map +1 -1
  5. package/dist/errors.d.mts.map +1 -1
  6. package/dist/errors.mjs.map +1 -1
  7. package/dist/flow-experimental.cjs +286 -0
  8. package/dist/flow-experimental.cjs.map +1 -0
  9. package/dist/flow-experimental.d.cts +69 -0
  10. package/dist/flow-experimental.d.cts.map +1 -0
  11. package/dist/flow-experimental.d.mts +69 -0
  12. package/dist/flow-experimental.d.mts.map +1 -0
  13. package/dist/flow-experimental.mjs +284 -0
  14. package/dist/flow-experimental.mjs.map +1 -0
  15. package/dist/flow.cjs +296 -0
  16. package/dist/flow.cjs.map +1 -0
  17. package/dist/flow.d.cts +79 -0
  18. package/dist/flow.d.cts.map +1 -0
  19. package/dist/flow.d.mts +79 -0
  20. package/dist/flow.d.mts.map +1 -0
  21. package/dist/flow.mjs +294 -0
  22. package/dist/flow.mjs.map +1 -0
  23. package/dist/index.cjs +26 -11
  24. package/dist/index.d.cts +8 -3
  25. package/dist/index.d.mts +8 -3
  26. package/dist/index.mjs +8 -3
  27. package/dist/match.cjs +282 -0
  28. package/dist/match.cjs.map +1 -1
  29. package/dist/match.d.cts +471 -5
  30. package/dist/match.d.cts.map +1 -1
  31. package/dist/match.d.mts +471 -5
  32. package/dist/match.d.mts.map +1 -1
  33. package/dist/match.mjs +277 -1
  34. package/dist/match.mjs.map +1 -1
  35. package/dist/option-experimental.cjs +1503 -0
  36. package/dist/option-experimental.cjs.map +1 -0
  37. package/dist/option-experimental.d.cts +1383 -0
  38. package/dist/option-experimental.d.cts.map +1 -0
  39. package/dist/option-experimental.d.mts +1383 -0
  40. package/dist/option-experimental.d.mts.map +1 -0
  41. package/dist/option-experimental.mjs +1501 -0
  42. package/dist/option-experimental.mjs.map +1 -0
  43. package/dist/option.cjs +556 -29
  44. package/dist/option.cjs.map +1 -1
  45. package/dist/option.d.cts +505 -24
  46. package/dist/option.d.cts.map +1 -1
  47. package/dist/option.d.mts +505 -24
  48. package/dist/option.d.mts.map +1 -1
  49. package/dist/option.mjs +556 -30
  50. package/dist/option.mjs.map +1 -1
  51. package/dist/result-experimental.cjs +1266 -0
  52. package/dist/result-experimental.cjs.map +1 -0
  53. package/dist/result-experimental.d.cts +1127 -0
  54. package/dist/result-experimental.d.cts.map +1 -0
  55. package/dist/result-experimental.d.mts +1127 -0
  56. package/dist/result-experimental.d.mts.map +1 -0
  57. package/dist/result-experimental.mjs +1265 -0
  58. package/dist/result-experimental.mjs.map +1 -0
  59. package/dist/result.cjs +715 -122
  60. package/dist/result.cjs.map +1 -1
  61. package/dist/result.d.cts +785 -94
  62. package/dist/result.d.cts.map +1 -1
  63. package/dist/result.d.mts +785 -94
  64. package/dist/result.d.mts.map +1 -1
  65. package/dist/result.mjs +714 -117
  66. package/dist/result.mjs.map +1 -1
  67. package/dist/tuple.cjs +3 -0
  68. package/dist/tuple.cjs.map +1 -1
  69. package/dist/tuple.d.cts +5 -1
  70. package/dist/tuple.d.cts.map +1 -1
  71. package/dist/tuple.d.mts +5 -1
  72. package/dist/tuple.d.mts.map +1 -1
  73. package/dist/tuple.mjs +2 -0
  74. package/dist/tuple.mjs.map +1 -1
  75. package/dist/unit.cjs +2 -0
  76. package/dist/unit.cjs.map +1 -1
  77. package/dist/unit.d.cts +2 -0
  78. package/dist/unit.d.cts.map +1 -1
  79. package/dist/unit.d.mts +2 -0
  80. package/dist/unit.d.mts.map +1 -1
  81. package/dist/unit.mjs +1 -0
  82. package/dist/unit.mjs.map +1 -1
  83. package/dist/utils.cjs +15 -0
  84. package/dist/utils.cjs.map +1 -1
  85. package/dist/utils.d.cts +10 -1
  86. package/dist/utils.d.cts.map +1 -1
  87. package/dist/utils.d.mts +10 -1
  88. package/dist/utils.d.mts.map +1 -1
  89. package/dist/utils.mjs +13 -1
  90. package/dist/utils.mjs.map +1 -1
  91. package/examples/README.md +46 -0
  92. package/examples/flow/01-basics.ts +74 -0
  93. package/examples/flow/02-async.ts +73 -0
  94. package/examples/flow/03-recovery.ts +60 -0
  95. package/examples/flow/04-complex-backend.ts +237 -0
  96. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  97. package/examples/flow/index.ts +13 -0
  98. package/examples/flow-experimental/01-basics.ts +78 -0
  99. package/examples/flow-experimental/02-async.ts +77 -0
  100. package/examples/flow-experimental/03-recovery.ts +93 -0
  101. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  102. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  103. package/examples/flow-experimental/index.ts +14 -0
  104. package/examples/match/01-stable-match.ts +147 -0
  105. package/examples/match/index.ts +19 -0
  106. package/examples/match-experimental/01-experimental-match.ts +150 -0
  107. package/examples/match-experimental/index.ts +18 -0
  108. package/examples/option/01-basics.ts +16 -0
  109. package/examples/option/02-map-flatMap.ts +36 -0
  110. package/examples/option/03-zip-flatZip.ts +23 -0
  111. package/examples/option/04-constructors.ts +21 -0
  112. package/examples/option/05-transform.ts +15 -0
  113. package/examples/option/06-aggregation.ts +14 -0
  114. package/examples/option/index.ts +49 -0
  115. package/examples/option-experimental/01-map.ts +109 -0
  116. package/examples/option-experimental/02-flatMap.ts +234 -0
  117. package/examples/option-experimental/03-zip.ts +197 -0
  118. package/examples/option-experimental/04-flatZip.ts +251 -0
  119. package/examples/option-experimental/05-gen.ts +360 -0
  120. package/examples/option-experimental/06-genAdapter.ts +463 -0
  121. package/examples/option-experimental/07-asyncGen.ts +353 -0
  122. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  123. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  124. package/examples/option-experimental/10-workflow-async.ts +378 -0
  125. package/examples/option-experimental/index.ts +341 -0
  126. package/examples/option-experimental/shared-domain.ts +325 -0
  127. package/examples/result/01-basics.ts +16 -0
  128. package/examples/result/02-map-flatMap.ts +34 -0
  129. package/examples/result/03-zip-flatZip.ts +23 -0
  130. package/examples/result/04-validation.ts +44 -0
  131. package/examples/result/05-constructors.ts +30 -0
  132. package/examples/result/06-utilities.ts +36 -0
  133. package/examples/result/index.ts +53 -0
  134. package/examples/result-experimental/01-map.ts +60 -0
  135. package/examples/result-experimental/02-flatMap.ts +169 -0
  136. package/examples/result-experimental/03-zip.ts +145 -0
  137. package/examples/result-experimental/04-flatZip.ts +252 -0
  138. package/examples/result-experimental/05-gen.ts +293 -0
  139. package/examples/result-experimental/06-genAdapter.ts +396 -0
  140. package/examples/result-experimental/07-asyncGen.ts +379 -0
  141. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  142. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  143. package/examples/result-experimental/10-workflow-async.ts +356 -0
  144. package/examples/result-experimental/index.ts +312 -0
  145. package/examples/result-experimental/shared-domain.ts +263 -0
  146. package/package.json +50 -18
package/README.md CHANGED
@@ -35,13 +35,13 @@ 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
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)
@@ -105,6 +110,15 @@ matchOpt(res, {
105
110
  - [Synchronous Pipeline](#synchronous-pipeline)
106
111
  - [Asynchronous Pipeline](#asynchronous-pipeline)
107
112
 
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
+
108
122
  ## Usage
109
123
 
110
124
  ## The `Result` type
@@ -118,6 +132,21 @@ const res1: Result<number, string> = Result.Ok(5); // Contains the value 5
118
132
  const res2: Result<number, string> = Result.Err("Some Error"); // Contains the error "Some Error"
119
133
  ```
120
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
+
121
150
  ## The `Option` type
122
151
 
123
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`.
@@ -129,6 +158,117 @@ const opt1: Option<number> = Option.Some(5); // Contains the value 5
129
158
  const opt2: Option<number> = Option.None; // Contains no value (None)
130
159
  ```
131
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
+
132
272
  ---
133
273
 
134
274
  ## Cheatsheet
@@ -137,6 +277,8 @@ const opt2: Option<number> = Option.None; // Contains no value (None)
137
277
 
138
278
  Transforms the `Some` or `Ok` value inside `Option` or `Result`.
139
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
+
140
282
  Let's say we want to apply a 10% bonus to the account balance of a user.
141
283
 
142
284
  ```typescript
@@ -159,7 +301,7 @@ async function applyBonus() {
159
301
  return balanceOption;
160
302
  }
161
303
 
162
- console.log(await applyBonus()); // Output: Some(110)
304
+ console.log(await applyBonus()); // Example output: Some(110)
163
305
  ```
164
306
 
165
307
  #### `flatMap`
@@ -206,7 +348,7 @@ const processUser = async (
206
348
  return validationResult;
207
349
  };
208
350
 
209
- 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!")
210
352
 
211
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) */
212
354
  ```
@@ -237,14 +379,14 @@ async function applyDiscount(
237
379
  return originalPrice; //originalPrice is of type Result<[number, number], Error>
238
380
  }
239
381
 
240
- console.log(await applyDiscount("123")); // Output: Result.Ok([100, 90])
382
+ console.log(await applyDiscount("123")); // Example output: Result.Ok([100, 90])
241
383
  ```
242
384
 
243
385
  Here `derivedPair` is a `Result<[number, number], Error>`. Note that `T` = `100` and `U` = `90`.
244
386
 
245
387
  #### `flatZip`
246
388
 
247
- 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`.
248
390
 
249
391
  Lets say we want to combine the product price and product stock into a tuple `[number, number]`.
250
392
 
@@ -258,10 +400,10 @@ async function fetchProductPrice(productId: string): Promise<Option<number>> {
258
400
  return Option.Some(100);
259
401
  }
260
402
 
261
- // Simulated function to fetch product stock
262
- async function fetchProductStock(productId: string): Promise<Option<number>> {
263
- // Simulate fetching stock from a database
264
- 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);
265
407
  return Option.Some(50);
266
408
  }
267
409
 
@@ -276,18 +418,18 @@ async function fetchProductDetails(
276
418
  return productDetails; // Option<[number, number]>
277
419
  }
278
420
 
279
- console.log(await fetchProductDetails("123")); // Output: Option.Some([100, 50])
421
+ console.log(await fetchProductDetails("123")); // Example output: Option.Some([100, 50])
280
422
  ```
281
423
 
282
424
  ## Comparison of `map`, `flatMap`, `zip`, and `flatZip`
283
425
 
284
426
  | **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** |
285
427
  | --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
286
- | **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]`. |
287
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`. |
288
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]>`. |
289
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. |
290
- | **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. |
291
433
 
292
434
  ---
293
435
 
@@ -338,18 +480,15 @@ async function findUserById(id: number): Promise<Option<number>> {
338
480
  return Option.Some(id);
339
481
  }
340
482
 
341
- // A safe function that returns a string error message if the user is not found, instead of throwing an exception
342
- async function safeFindUserById(id: number): Promise<Option<string>> {
343
- const res = (await findUserById(id)).mapOr(
344
- `User not found`,
345
- (res) => `User: ${res}`,
346
- );
347
- 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}`);
348
487
  }
349
488
 
350
489
  // Example usage
351
- console.log(await safeFindUserById(10)); // Some(User: 10)
352
- 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
353
492
  ```
354
493
 
355
494
  #### `all`
@@ -383,6 +522,7 @@ type Like = {
383
522
  type Reply = {
384
523
  replyId: string;
385
524
  postId: Post["postId"];
525
+ data: string;
386
526
  createdAt: Date | string;
387
527
  author: User["userId"];
388
528
  };
@@ -447,11 +587,11 @@ async function getUserData(userId: string) {
447
587
  const hash = userIdRes.flatMap(generateHash);
448
588
 
449
589
  const userData = await Result.all(
450
- user, // Result<Promise<T>, E>
451
- posts, // Result<Promise<T>, E>
452
- likes, // Result<Promise<T>, E>
453
- replies, // Result<Promise<T>, E>
454
- hash, // Result<T, E>
590
+ user,
591
+ posts,
592
+ likes,
593
+ replies,
594
+ hash,
455
595
  ).toPromise();
456
596
 
457
597
  matchRes(userData, {
@@ -547,9 +687,10 @@ const validatedOk = Result.Ok("password321!").validate([
547
687
  ]);
548
688
  console.log(validatedOk.unwrap()); // password321!
549
689
 
550
- const validatedErr = await Result.Ok("pword")
551
- .validate([hasMinimumLength, hasSpecialCharacters])
552
- .toPromise();
690
+ const validatedErr = Result.Ok("pword").validate([
691
+ hasMinimumLength,
692
+ hasSpecialCharacters,
693
+ ]);
553
694
  console.log(validatedErr.unwrapErr()); // [Error: Password must be at least 8 characters, Error: Password must contain at least one special character]
554
695
 
555
696
  const validatedErrs = await Result.Ok("password123!")
@@ -558,7 +699,7 @@ const validatedErrs = await Result.Ok("password123!")
558
699
  console.log(validatedErrs.unwrapErr()); // [Error: New password cannot be the same as previous password]
559
700
  ```
560
701
 
561
- #### `unwrap`, `safeUnwrapErr`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
702
+ #### `unwrap`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
562
703
 
563
704
  These functions are used to extract the value from a `Result`. Note that **only `unwrap` and `safeUnwrap` are available for `Option`**.
564
705
 
@@ -660,11 +801,7 @@ Creates a `Result` based on a predicate function - returns `Ok` with the value i
660
801
  import { Result } from "@carbonteq/fp";
661
802
 
662
803
  const score = 85;
663
- const passed = Result.fromPredicate(
664
- score,
665
- (s) => s >= 60,
666
- "Score too low",
667
- );
804
+ const passed = Result.fromPredicate(score, (s) => s >= 60, "Score too low");
668
805
  console.log(passed); // Ok(85)
669
806
 
670
807
  const failed = Result.fromPredicate(45, (s) => s >= 60, "Score too low");
@@ -685,7 +822,7 @@ import { Result } from "@carbonteq/fp";
685
822
  function parseJson(json: string): Result<unknown, Error> {
686
823
  return Result.tryCatch(
687
824
  () => JSON.parse(json),
688
- (e) => e instanceof Error ? e : new Error(String(e)),
825
+ (e) => (e instanceof Error ? e : new Error(String(e))),
689
826
  );
690
827
  }
691
828
 
@@ -700,17 +837,19 @@ Wraps an asynchronous operation in a `Result`, catching any exceptions and conve
700
837
  ```typescript
701
838
  import { Result } from "@carbonteq/fp";
702
839
 
703
- async function fetchUserData(id: string): Result<Promise<{ name: string }>, Error> {
840
+ async function fetchUserData(
841
+ id: string,
842
+ ): Promise<Result<{ name: string }, Error>> {
704
843
  return Result.tryAsyncCatch(
705
844
  async () => {
706
845
  const response = await fetch(`/api/users/${id}`);
707
846
  return response.json();
708
847
  },
709
- (e) => e instanceof Error ? e : new Error(String(e)),
848
+ (e) => (e instanceof Error ? e : new Error(String(e))),
710
849
  );
711
850
  }
712
851
 
713
- const user = await fetchUserData("123").toPromise();
852
+ const user = await fetchUserData("123");
714
853
  console.log(user); // Ok({ name: "..." }) or Err(Error: ...)
715
854
  ```
716
855
 
@@ -814,36 +953,6 @@ const optFromErr = failure.toOption();
814
953
  console.log(optFromErr); // None
815
954
  ```
816
955
 
817
- #### `Option.fromPromise`
818
-
819
- Wraps a `Promise<Option<T>>` as an `Option<Promise<T>>`, enabling async chaining.
820
-
821
- ```typescript
822
- import { Option } from "@carbonteq/fp";
823
-
824
- async function fetchUser(id: string): Promise<Option<{ name: string }>> {
825
- return id === "1" ? Option.Some({ name: "Alice" }) : Option.None;
826
- }
827
-
828
- const userOpt = Option.fromPromise(fetchUser("1"));
829
- console.log(userOpt); // Some(Promise<{ name: "Alice" }>)
830
- ```
831
-
832
- #### `Result.fromPromise`
833
-
834
- Wraps a `Promise<Result<T, E>>` as a `Result<Promise<T>, E>`, enabling async chaining.
835
-
836
- ```typescript
837
- import { Result } from "@carbonteq/fp";
838
-
839
- async function fetchData(id: string): Promise<Result<string, Error>> {
840
- return id === "1" ? Result.Ok("Data") : Result.Err(new Error("Not found"));
841
- }
842
-
843
- const dataRes = Result.fromPromise(fetchData("1"));
844
- console.log(dataRes); // Ok(Promise<"Data">)
845
- ```
846
-
847
956
  #### `Result.zipErr`
848
957
 
849
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.
@@ -853,7 +962,9 @@ import { Result } from "@carbonteq/fp";
853
962
 
854
963
  const checkPermissions = (userId: string) =>
855
964
  Result.Ok(userId).zipErr((id) =>
856
- id === "guest" ? Result.Err("Guest users have limited access") : Result.Ok(undefined)
965
+ id === "guest"
966
+ ? Result.Err("Guest users have limited access")
967
+ : Result.Ok(undefined),
857
968
  );
858
969
 
859
970
  const admin = checkPermissions("admin-123");
@@ -865,8 +976,9 @@ console.log(guest); // Err("Guest users have limited access")
865
976
  const okNoChange = Result.Ok("42").zipErr((id) => Result.Ok(id.length));
866
977
  console.log(okNoChange); // Ok("42")
867
978
 
868
- const alreadyFailed = Result.Err<string, string>("Network error")
869
- .zipErr(() => Result.Err("Validation error"));
979
+ const alreadyFailed = Result.Err<string, string>("Network error").zipErr(() =>
980
+ Result.Err("Validation error"),
981
+ );
870
982
  console.log(alreadyFailed); // Err("Network error") - short-circuits
871
983
  ```
872
984
 
@@ -877,17 +989,18 @@ console.log(alreadyFailed); // Err("Network error") - short-circuits
877
989
  ```typescript
878
990
  import { Result } from "@carbonteq/fp";
879
991
 
880
- const res = Result.Err<number, Error>(new Error("boom"))
881
- .mapErr((e) => e.message);
992
+ const res = Result.Err<Error, number>(new Error("boom")).mapErr(
993
+ (e) => e.message,
994
+ );
882
995
  console.log(res); // Err("boom")
883
996
 
884
997
  const ok = Result.Ok("42").zipErr((value) =>
885
- value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
998
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
886
999
  );
887
1000
  console.log(ok); // Ok("42")
888
1001
 
889
1002
  const err = Result.Ok("0").zipErr((value) =>
890
- value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
1003
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length),
891
1004
  );
892
1005
  console.log(err); // Err("invalid")
893
1006
  ```
@@ -920,7 +1033,9 @@ Executes a side effect function for `Some` or `Ok` values, then returns the orig
920
1033
  import { Result } from "@carbonteq/fp";
921
1034
 
922
1035
  // Simulated database functions
923
- async function findUserById(userId: number): Promise<Result<Record<string, number>, string>> {
1036
+ async function findUserById(
1037
+ userId: number,
1038
+ ): Promise<Result<Record<string, number>, string>> {
924
1039
  // Simulate a database lookup
925
1040
  await Promise.resolve(userId);
926
1041
  if (userId === 0) {
@@ -929,7 +1044,10 @@ async function findUserById(userId: number): Promise<Result<Record<string, numbe
929
1044
  return Result.Ok({ id: userId, balance: 100 });
930
1045
  }
931
1046
 
932
- function updateBalance(user: Record<string, number>, amount: number): Result<Record<string, number>, string> {
1047
+ function updateBalance(
1048
+ user: Record<string, number>,
1049
+ amount: number,
1050
+ ): Result<Record<string, number>, string> {
933
1051
  if (user.balance < amount) {
934
1052
  return Result.Err("Insufficient funds");
935
1053
  }
@@ -940,7 +1058,9 @@ function updateBalance(user: Record<string, number>, amount: number): Result<Rec
940
1058
  const res = (await findUserById(1))
941
1059
  .tap((user) => console.log(`[Audit] User found: ${user.id}`))
942
1060
  .flatMap((user) => updateBalance(user, 10))
943
- .tap((updated) => console.log(`[Transaction] New balance: $${updated.balance}`))
1061
+ .tap((updated) =>
1062
+ console.log(`[Transaction] New balance: $${updated.balance}`),
1063
+ )
944
1064
  .tapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
945
1065
 
946
1066
  console.log(res); // Result.Ok({ id: 1, balance: 90 })
@@ -958,7 +1078,7 @@ const logged = result.tapErr((err) => {
958
1078
  console.error(`[Error Log] ${new Date().toISOString()}: ${err}`);
959
1079
  });
960
1080
  console.log(logged); // Err("Connection failed")
961
- // Output: [Error Log] 2025-01-07T...: Connection failed
1081
+ // Example output: [Error Log] 2025-01-07T...: Connection failed
962
1082
  ```
963
1083
 
964
1084
  #### `Result.orElse`
@@ -969,11 +1089,15 @@ Recovers from an error by providing a fallback `Result`. If the current result i
969
1089
  import { Result } from "@carbonteq/fp";
970
1090
 
971
1091
  function fetchFromCache(id: string): Result<string, Error> {
972
- return id === "cached" ? Result.Ok("Cached data") : Result.Err(new Error("Not in cache"));
1092
+ return id === "cached"
1093
+ ? Result.Ok("Cached data")
1094
+ : Result.Err(new Error("Not in cache"));
973
1095
  }
974
1096
 
975
1097
  function fetchFromAPI(id: string): Result<string, Error> {
976
- return id === "1" ? Result.Ok("API data") : Result.Err(new Error("Not found"));
1098
+ return id === "1"
1099
+ ? Result.Ok("API data")
1100
+ : Result.Err(new Error("Not found"));
977
1101
  }
978
1102
 
979
1103
  const cached = fetchFromCache("cached").orElse((err) => fetchFromAPI("1"));
@@ -1008,6 +1132,51 @@ const allNone = Option.any(Option.None, Option.None, Option.None);
1008
1132
  console.log(allNone); // None
1009
1133
  ```
1010
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
+
1011
1180
  #### `Result.any`
1012
1181
 
1013
1182
  Returns the first `Ok` from a list of `Result`s, or collects all errors if all are `Err`.
@@ -1030,6 +1199,53 @@ const allErrors = Result.any(
1030
1199
  console.log(allErrors); // Err(["Error 1", "Error 2", "Error 3"])
1031
1200
  ```
1032
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
+
1033
1249
  ## Build Your First Pipeline
1034
1250
 
1035
1251
  Let's build a pipeline for processing an e-commerce order. This example demonstrates handling user input validation, inventory checks, and order processing.
@@ -1108,7 +1324,7 @@ matchRes(result, {
1108
1324
  },
1109
1325
  });
1110
1326
 
1111
- // Output:
1327
+ // Example output:
1112
1328
  // Order confirmed! Order ID: ORD-1716888600000
1113
1329
  // Total: $59.98
1114
1330
  // Order: {"productId":"PROD-123","quantity":2,"userId":"USER-456"}
@@ -1119,8 +1335,7 @@ matchRes(result, {
1119
1335
  Let's build an asynchronous pipeline for a user registration system that includes credentials verification and profile setup.
1120
1336
 
1121
1337
  ```typescript
1122
- import { matchRes } from "@/match.js";
1123
- import { Result } from "@/result.js";
1338
+ import { matchRes, Result } from "@carbonteq/fp";
1124
1339
 
1125
1340
  interface UserInput {
1126
1341
  email: string;
@@ -1185,13 +1400,12 @@ async function sendVerificationEmail(
1185
1400
  return Result.Ok(profile);
1186
1401
  }
1187
1402
 
1188
- // Main registration pipeline
1403
+ // Main registration pipeline using validate + flatMap
1189
1404
  async function registerUser(
1190
1405
  input: UserInput,
1191
1406
  ): Promise<Result<UserProfile, string | string[]>> {
1192
1407
  const res = await Result.Ok(input)
1193
1408
  .validate([
1194
- // handles both sync and async functions
1195
1409
  ({ email }) => guardEmail(email),
1196
1410
  ({ email }) => guardEmailAvailability(email),
1197
1411
  ({ password }) => guardPassword(password),
@@ -1227,7 +1441,7 @@ async function main() {
1227
1441
  }
1228
1442
 
1229
1443
  main();
1230
- // Output:
1444
+ // Example output:
1231
1445
  // Verification email sent to newuser@example.com
1232
1446
  // Email: newuser@example.com
1233
1447
  // Registration successful!