@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
@@ -0,0 +1,147 @@
1
+ /**
2
+ * match() API examples for stable Option/Result.
3
+ *
4
+ * This file demonstrates:
5
+ * - String-tag matching
6
+ * - Pattern helpers (P.Some/P.Ok/etc)
7
+ * - Guards and fallthrough
8
+ * - Generic discriminated unions
9
+ * - How to handle Option<Promise<T>> / Result<Promise<T>, E>
10
+ */
11
+
12
+ import { match, P } from "../../dist/match.mjs"
13
+ import { Option } from "../../dist/option.mjs"
14
+ import { Result } from "../../dist/result.mjs"
15
+
16
+ console.log("=== Stable match() examples ===\n")
17
+
18
+ // -----------------------------------------------------------------------------
19
+ // 1) Basic Option/Result matching
20
+ // -----------------------------------------------------------------------------
21
+
22
+ const maybeScore = Option.Some(82)
23
+ const grade = match(maybeScore)
24
+ .with("Some", (value) => (value >= 90 ? "A" : "B"))
25
+ .with("None", () => "N/A")
26
+ .exhaustive()
27
+ console.log("grade:", grade)
28
+
29
+ const apiResult = Result.Err("rate-limited") as Result<number, string>
30
+ const label = match(apiResult)
31
+ .with("Ok", (value) => `value=${value}`)
32
+ .with("Err", (error) => `error=${error}`)
33
+ .exhaustive()
34
+ console.log("result label:", label)
35
+
36
+ // -----------------------------------------------------------------------------
37
+ // 2) P helpers + guards
38
+ // -----------------------------------------------------------------------------
39
+
40
+ const guarded = match(Option.Some(74))
41
+ .with(
42
+ P.Some((x: number) => x >= 90),
43
+ () => "A",
44
+ )
45
+ .with(
46
+ P.Some((x: number) => x >= 80),
47
+ () => "B",
48
+ )
49
+ .with(
50
+ P.Some((x: number) => x >= 70),
51
+ () => "C",
52
+ )
53
+ .with(P.Some(), () => "D")
54
+ .with(P.None(), () => "N/A")
55
+ .exhaustive()
56
+ console.log("guarded grade:", guarded)
57
+
58
+ const retryPolicy = match(Result.Err("fatal") as Result<number, string>)
59
+ .with(P.Ok(), () => "none")
60
+ .with(P.Err(P.oneOf("timeout", "offline")), () => "retry")
61
+ .with(P.Err(P.not(P.oneOf("timeout", "offline"))), () => "do-not-retry")
62
+ .exhaustive()
63
+ console.log("retry policy:", retryPolicy)
64
+
65
+ const stateByPredicates = match(Result.Ok(1) as Result<number, string>)
66
+ .when(P.IsErr, () => "err")
67
+ .when(P.IsOk, () => "ok")
68
+ .otherwise(() => "other")
69
+ console.log("state by predicates:", stateByPredicates)
70
+
71
+ const combinedPredicates = match(Result.Ok(42) as Result<number, string>)
72
+ .with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
73
+ .with(P.Ok(), () => "miss")
74
+ .with(P.Err(), () => "err")
75
+ .exhaustive()
76
+ console.log("combined predicates:", combinedPredicates)
77
+
78
+ // -----------------------------------------------------------------------------
79
+ // 3) when() + otherwise() + wildcard
80
+ // -----------------------------------------------------------------------------
81
+
82
+ const status = match(Result.Ok({ attempts: 4, user: "alice" }))
83
+ .when(
84
+ (r) => r.isOk() && r.unwrap().attempts > 3,
85
+ () => "needs-review",
86
+ )
87
+ .with(P._, () => "ok")
88
+ .exhaustive()
89
+ console.log("status:", status)
90
+
91
+ const fallbackStatus = match(Result.Err("boom") as Result<number, string>)
92
+ .with(P.Ok(P.not(P.eq(42))), () => "ok-not-42")
93
+ .with(P.Ok(P.eq(42)), () => "ok-42")
94
+ .otherwise(() => "fallback")
95
+ console.log("fallback status:", fallbackStatus)
96
+
97
+ // -----------------------------------------------------------------------------
98
+ // 4) Generic discriminated union support
99
+ // -----------------------------------------------------------------------------
100
+
101
+ type JobEvent =
102
+ | { readonly _tag: "queued"; id: string }
103
+ | { readonly _tag: "running"; id: string; progress: number }
104
+ | { readonly _tag: "failed"; id: string; reason: string }
105
+
106
+ const asJobEvent = (value: JobEvent): JobEvent => value
107
+ const event = asJobEvent({ _tag: "running", id: "job-1", progress: 55 })
108
+ const eventText = match(event)
109
+ .with("queued", (e) => `queued:${e.id}`)
110
+ .with("running", (e) => `running:${e.id}:${e.progress}%`)
111
+ .with("failed", (e) => `failed:${e.id}:${e.reason}`)
112
+ .exhaustive()
113
+ console.log("event:", eventText)
114
+
115
+ // -----------------------------------------------------------------------------
116
+ // 5) Async-inner stable values: settle first, then match
117
+ // -----------------------------------------------------------------------------
118
+
119
+ async function runAsyncInnerExamples(): Promise<void> {
120
+ // IMPORTANT:
121
+ // match() intentionally rejects Result<Promise<T>, E> and Option<Promise<T>>.
122
+ // For stable variants, convert them first with toPromise():
123
+ // Result<Promise<T>, E> -> Promise<Result<T, E>>
124
+ // Option<Promise<T>> -> Promise<Option<T>>
125
+
126
+ const asyncStableResult = Result.Ok(Promise.resolve(21))
127
+ const settledResult = await asyncStableResult.toPromise()
128
+
129
+ const settledResultText = match(settledResult)
130
+ .with("Ok", (value) => `settled-ok:${value * 2}`)
131
+ .with("Err", (error) => `settled-err:${String(error)}`)
132
+ .exhaustive()
133
+ console.log("settled result:", settledResultText)
134
+
135
+ const asyncStableOption = Option.Some(Promise.resolve("token-123"))
136
+ const settledOption = await asyncStableOption.toPromise()
137
+
138
+ const settledOptionText = match(settledOption)
139
+ .with("Some", (value) => `settled-some:${value}`)
140
+ .with("None", () => "settled-none")
141
+ .exhaustive()
142
+ console.log("settled option:", settledOptionText)
143
+ }
144
+
145
+ await runAsyncInnerExamples()
146
+
147
+ console.log("\n=== stable match() examples complete ===")
@@ -0,0 +1,19 @@
1
+ /**
2
+ * match() Examples Index (Stable)
3
+ *
4
+ * Run:
5
+ * bun run examples/match/01-stable-match.ts
6
+ */
7
+
8
+ /**
9
+ * 01-stable-match.ts
10
+ *
11
+ * Topics covered:
12
+ * - match() with stable Option/Result
13
+ * - P helpers and guarded cases
14
+ * - wildcard/when/otherwise
15
+ * - generic discriminated unions
16
+ * - async-inner stable values via toPromise()
17
+ */
18
+
19
+ export {}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * match() API examples for experimental Option/Result.
3
+ *
4
+ * This file demonstrates:
5
+ * - Matching ExperimentalOption / ExperimentalResult
6
+ * - Guards and wildcard patterns
7
+ * - Discriminated-union matching
8
+ * - How to handle async workflows before matching
9
+ */
10
+
11
+ import { match, P } from "../../dist/match.mjs"
12
+ import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
13
+ import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
14
+
15
+ console.log("=== Experimental match() examples ===\n")
16
+
17
+ // -----------------------------------------------------------------------------
18
+ // 1) Basic matching
19
+ // -----------------------------------------------------------------------------
20
+
21
+ const maybeUserId = Option.Some(7)
22
+ const userBucket = match(maybeUserId)
23
+ .with("Some", (id) => (id > 5 ? "active" : "new"))
24
+ .with("None", () => "guest")
25
+ .exhaustive()
26
+ console.log("user bucket:", userBucket)
27
+
28
+ const networkResult = Result.Ok({ retries: 1 })
29
+ const networkText = match(networkResult)
30
+ .with("Ok", (value) => `ok:retries=${value.retries}`)
31
+ .with("Err", (error) => `err:${String(error)}`)
32
+ .exhaustive()
33
+ console.log("network:", networkText)
34
+
35
+ // -----------------------------------------------------------------------------
36
+ // 2) Guarded patterns
37
+ // -----------------------------------------------------------------------------
38
+
39
+ const severity = match(Result.Err({ code: 503, message: "unavailable" }))
40
+ .with(P.Ok(), () => "ok")
41
+ .with(
42
+ P.Err((e: { code: number }) => e.code >= 500),
43
+ () => "server",
44
+ )
45
+ .with(
46
+ P.Err((e: { code: number }) => e.code >= 400),
47
+ () => "client",
48
+ )
49
+ .with(P.Err(), () => "unknown")
50
+ .exhaustive()
51
+ console.log("severity:", severity)
52
+
53
+ const alerting = match(Result.Err("fatal") as Result<number, string>)
54
+ .with(P.Ok(P.eq(42)), () => "special")
55
+ .with(P.Ok(), () => "ok")
56
+ .with(P.Err(P.oneOf("timeout", "offline")), () => "warn")
57
+ .with(P.Err(P.not(P.oneOf("timeout", "offline"))), () => "critical")
58
+ .exhaustive()
59
+ console.log("alerting:", alerting)
60
+
61
+ const stateByPredicates = match(Option.None as Option<number>)
62
+ .when(P.IsSome, () => "some")
63
+ .when(P.IsNone, () => "none")
64
+ .otherwise(() => "other")
65
+ console.log("state by predicates:", stateByPredicates)
66
+
67
+ const combinedPredicates = match(Result.Ok(43) as Result<number, string>)
68
+ .with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
69
+ .with(P.Ok(), () => "miss")
70
+ .with(P.Err(), () => "err")
71
+ .exhaustive()
72
+ console.log("combined predicates:", combinedPredicates)
73
+
74
+ // -----------------------------------------------------------------------------
75
+ // 3) Generic discriminated unions
76
+ // -----------------------------------------------------------------------------
77
+
78
+ type PaymentState =
79
+ | { readonly _tag: "started"; id: string }
80
+ | { readonly _tag: "authorized"; id: string; amount: number }
81
+ | { readonly _tag: "declined"; id: string; reason: string }
82
+
83
+ const asPaymentState = (value: PaymentState): PaymentState => value
84
+
85
+ const payment = asPaymentState({
86
+ _tag: "authorized",
87
+ id: "pay-22",
88
+ amount: 199,
89
+ })
90
+
91
+ const paymentText = match(payment)
92
+ .with("started", (p) => `started:${p.id}`)
93
+ .with("authorized", (p) => `authorized:${p.id}:${p.amount}`)
94
+ .with("declined", (p) => `declined:${p.id}:${p.reason}`)
95
+ .exhaustive()
96
+ console.log("payment:", paymentText)
97
+
98
+ // -----------------------------------------------------------------------------
99
+ // 4) Async workflows with experimental types
100
+ // -----------------------------------------------------------------------------
101
+
102
+ async function loadQuota(id: number): Promise<Result<number, string>> {
103
+ return id > 0 ? Result.Ok(100 + id) : Result.Err("invalid-id")
104
+ }
105
+
106
+ async function runAsyncExamples(): Promise<void> {
107
+ // Preferred with experimental APIs:
108
+ // run async operations first (mapAsync/flatMapAsync/own async function),
109
+ // then match the settled ExperimentalResult/ExperimentalOption value.
110
+
111
+ const settledResult = await loadQuota(3)
112
+ const quotaText = match(settledResult)
113
+ .with("Ok", (quota) => `quota:${quota}`)
114
+ .with("Err", (error) => `quota-error:${error}`)
115
+ .exhaustive()
116
+ console.log("quota:", quotaText)
117
+
118
+ const settledOption = await Option.Some("admin").mapAsync(async (role) =>
119
+ role.toUpperCase(),
120
+ )
121
+
122
+ const roleText = match(settledOption)
123
+ .with("Some", (role) => `role:${role}`)
124
+ .with("None", () => "role:none")
125
+ .exhaustive()
126
+ console.log("role:", roleText)
127
+
128
+ const rolePolicy = match(settledOption)
129
+ .with(P.Some(P.not(P.eq("ADMIN"))), (role) => `limited:${role}`)
130
+ .with(P.Some(P.eq("ADMIN")), () => "full-access")
131
+ .with(P.None(), () => "no-access")
132
+ .exhaustive()
133
+ console.log("role policy:", rolePolicy)
134
+
135
+ // You can still construct Result<Promise<T>, E> manually, but match() does not
136
+ // accept async-inner values directly. Settle first, then wrap/match.
137
+ const manualAsyncInner = Result.Ok(Promise.resolve(9))
138
+ const settledValue = await manualAsyncInner.unwrap()
139
+ const settledManual = Result.Ok(settledValue)
140
+
141
+ const manualText = match(settledManual)
142
+ .with("Ok", (value) => `manual:${value}`)
143
+ .with("Err", () => "manual:err")
144
+ .exhaustive()
145
+ console.log("manual async-inner settled:", manualText)
146
+ }
147
+
148
+ await runAsyncExamples()
149
+
150
+ console.log("\n=== experimental match() examples complete ===")
@@ -0,0 +1,18 @@
1
+ /**
2
+ * match() Examples Index (Experimental)
3
+ *
4
+ * Run:
5
+ * bun run examples/match-experimental/01-experimental-match.ts
6
+ */
7
+
8
+ /**
9
+ * 01-experimental-match.ts
10
+ *
11
+ * Topics covered:
12
+ * - match() with ExperimentalOption/ExperimentalResult
13
+ * - guarded patterns and wildcard
14
+ * - discriminated-union matching
15
+ * - settling async workflows before matching
16
+ */
17
+
18
+ export {}
@@ -0,0 +1,16 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const some = Option.Some(5)
4
+ const none: Option<number> = Option.None
5
+
6
+ console.log("some isSome:", some.isSome())
7
+ console.log("none isNone:", none.isNone())
8
+
9
+ const matched = some.match({
10
+ Some: (value) => `Value: ${value}`,
11
+ None: () => "No value",
12
+ })
13
+
14
+ console.log("match:", matched)
15
+ console.log("unwrapOr:", none.unwrapOr(0))
16
+ console.log("safeUnwrap:", none.safeUnwrap())
@@ -0,0 +1,36 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const doubled = Option.Some(3).map((value) => value * 2)
4
+ console.log("map:", doubled.unwrap())
5
+
6
+ const fetchUserBalanceFromDatabase = async (
7
+ userId: string,
8
+ ): Promise<Option<number>> => {
9
+ await Promise.resolve(userId)
10
+ return Option.Some(100)
11
+ }
12
+
13
+ const applyBonus = async (): Promise<Option<number>> => {
14
+ return await Option.Some("user123")
15
+ .flatMap(fetchUserBalanceFromDatabase)
16
+ .map((balance) => balance * 1.1)
17
+ .toPromise()
18
+ }
19
+
20
+ const result = await applyBonus()
21
+ console.log("flatMap:", result.unwrap())
22
+
23
+ const findUserById = async (id: number): Promise<Option<number>> => {
24
+ await Promise.resolve(id)
25
+ return id === 0 ? Option.None : Option.Some(id)
26
+ }
27
+
28
+ const safeFindUserById = async (id: number): Promise<string> => {
29
+ const res = (await findUserById(id)).mapOr(
30
+ "User not found",
31
+ (value) => `User: ${value}`,
32
+ )
33
+ return res
34
+ }
35
+
36
+ console.log("mapOr:", await safeFindUserById(10))
@@ -0,0 +1,23 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const zipped = Option.Some(100).zip((price) => price * 0.9)
4
+ console.log("zip:", zipped.unwrap())
5
+
6
+ const fetchProductPrice = async (
7
+ productId: string,
8
+ ): Promise<Option<number>> => {
9
+ await Promise.resolve(productId)
10
+ return productId === "sku-1" ? Option.Some(120) : Option.None
11
+ }
12
+
13
+ const fetchProductStock = async (price: number): Promise<Option<number>> => {
14
+ await Promise.resolve(price)
15
+ return price > 0 ? Option.Some(42) : Option.None
16
+ }
17
+
18
+ const combined = await Option.Some("sku-1")
19
+ .flatMap(fetchProductPrice)
20
+ .flatZip(fetchProductStock)
21
+ .toPromise()
22
+
23
+ console.log("flatZip:", combined.unwrap())
@@ -0,0 +1,21 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const findUser = (id: string): { name: string } | null =>
4
+ id === "1" ? { name: "Alice" } : null
5
+
6
+ console.log("fromNullable:", Option.fromNullable(findUser("1")).unwrap())
7
+ console.log("fromNullable none:", Option.fromNullable(findUser("2")).isNone())
8
+
9
+ console.log("fromFalsy:", Option.fromFalsy("hello").unwrap())
10
+ console.log("fromFalsy none:", Option.fromFalsy(0).isNone())
11
+
12
+ console.log("fromPredicate:", Option.fromPredicate(25, (a) => a >= 18).unwrap())
13
+
14
+ const fetchUser = async (id: string): Promise<Option<{ name: string }>> => {
15
+ await Promise.resolve(id)
16
+ return id === "1" ? Option.Some({ name: "Alice" }) : Option.None
17
+ }
18
+
19
+ const userOpt = Option.fromPromise(fetchUser("1"))
20
+ const resolved = await userOpt.toPromise()
21
+ console.log("fromPromise:", resolved.unwrap())
@@ -0,0 +1,15 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const age = Option.Some(25)
4
+ const adult = age.filter((a) => a >= 18)
5
+ console.log("filter:", adult.unwrap())
6
+
7
+ const numbers = Option.Some([1, 2, 3, 4])
8
+ const doubled = numbers.innerMap((n) => n * 2)
9
+ console.log("innerMap:", doubled.unwrap())
10
+
11
+ const tapped = Option.Some("hello").tap((value) => {
12
+ console.log("tap:", value)
13
+ })
14
+
15
+ console.log("tap result:", tapped.unwrap())
@@ -0,0 +1,14 @@
1
+ import { Option } from "../../dist/option.mjs"
2
+
3
+ const all = Option.all(Option.Some(1), Option.Some(2), Option.Some(3))
4
+ console.log("all:", all.unwrap())
5
+
6
+ const first = Option.any(
7
+ Option.None,
8
+ Option.Some("First"),
9
+ Option.Some("Second"),
10
+ )
11
+ console.log("any:", first.unwrap())
12
+
13
+ const toResult = Option.Some({ name: "Alice" }).toResult("User not found")
14
+ console.log("toResult:", toResult.unwrap())
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Option Examples Index (Stable)
3
+ *
4
+ * These examples use the stable Option API.
5
+ * Run examples with:
6
+ * bun run examples/option/01-basics.ts
7
+ * bun run examples/option/02-map-flatMap.ts
8
+ * etc.
9
+ */
10
+
11
+ // ============================================================================
12
+ // BASICS (files 01-03)
13
+ // ============================================================================
14
+
15
+ /**
16
+ * 01-basics.ts - Some/None fundamentals and matching
17
+ * Run: bun run examples/option/01-basics.ts
18
+ */
19
+
20
+ /**
21
+ * 02-map-flatMap.ts - map, flatMap, and mapOr (sync + async)
22
+ * Run: bun run examples/option/02-map-flatMap.ts
23
+ */
24
+
25
+ /**
26
+ * 03-zip-flatZip.ts - zip and flatZip composition
27
+ * Run: bun run examples/option/03-zip-flatZip.ts
28
+ */
29
+
30
+ // ============================================================================
31
+ // CONSTRUCTORS & UTILITIES (files 04-06)
32
+ // ============================================================================
33
+
34
+ /**
35
+ * 04-constructors.ts - fromNullable, fromFalsy, fromPredicate, fromPromise
36
+ * Run: bun run examples/option/04-constructors.ts
37
+ */
38
+
39
+ /**
40
+ * 05-transform.ts - filter, innerMap, tap
41
+ * Run: bun run examples/option/05-transform.ts
42
+ */
43
+
44
+ /**
45
+ * 06-aggregation.ts - all, any, toResult
46
+ * Run: bun run examples/option/06-aggregation.ts
47
+ */
48
+
49
+ export {}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Option.map() - Transform the Some value
3
+ *
4
+ * map() applies a function to the Some value, leaving None unchanged.
5
+ * If the Option is None, the mapper function is NOT called.
6
+ */
7
+
8
+ import { ExperimentalOption as Option } from "../../dist/option-experimental.mjs"
9
+
10
+ // ============================================================================
11
+ // BASIC MAP EXAMPLES
12
+ // ============================================================================
13
+
14
+ console.log("=== Option.map() Examples ===\n")
15
+
16
+ // Example 1: Simple number transformation
17
+ const numberSome = Option.Some(5)
18
+ const doubled = numberSome.map((x) => x * 2)
19
+ console.log("1. Double 5:", doubled.unwrap()) // 10
20
+
21
+ // Example 2: Map on None - mapper is NOT called
22
+ const numberNone = Option.None
23
+ const doubledNone = numberNone.map((x) => {
24
+ console.log(" This will NOT be printed!")
25
+ return x * 2
26
+ })
27
+ console.log("2. Map on None:", doubledNone.toString()) // Option::None
28
+
29
+ // Example 3: Chaining multiple maps
30
+ const result = Option.Some(10)
31
+ .map((x) => x + 5)
32
+ .map((x) => x * 2)
33
+ .map((x) => x.toString())
34
+ console.log("3. Chain maps:", result.unwrap()) // "30"
35
+
36
+ // Example 4: Map to object
37
+ type UserId = number
38
+ type User = { id: UserId; name: string }
39
+
40
+ const userId = Option.Some(42)
41
+ const user = userId.map((id): User => ({ id, name: `User ${id}` }))
42
+ console.log("4. Map to object:", user.unwrap()) // { id: 42, name: "User 42" }
43
+
44
+ // Example 5: Map that transforms type
45
+ const parsed = Option.Some("123")
46
+ .map((str) => parseInt(str, 10))
47
+ .map((num) => num * 2)
48
+ console.log("5. Parse and double:", parsed.unwrap()) // 246
49
+
50
+ // Example 6: Map is synchronous - for async operations, use gen.async* methods
51
+ // See 07-asyncGen.ts and 08-asyncGenAdapter.ts for async patterns
52
+
53
+ // Example 7: Map with array operations
54
+ const numbers = Option.Some([1, 2, 3, 4, 5])
55
+ const sumSquared = numbers
56
+ .map((arr) => arr.filter((x) => x % 2 === 0))
57
+ .map((arr) => arr.reduce((sum, x) => sum + x, 0))
58
+ console.log("7. Filter and sum:", sumSquared.unwrap()) // 6 (2 + 4)
59
+
60
+ // Example 8: Map for type transformation
61
+ type SerializedUser = { user_id: number; display_name: string }
62
+
63
+ const userId2 = Option.Some(123)
64
+ const serialized = userId2.map(
65
+ (id): SerializedUser => ({
66
+ user_id: id,
67
+ display_name: `User_${id}`,
68
+ }),
69
+ )
70
+ console.log("8. Type transformation:", serialized.unwrap()) // { user_id: 123, display_name: "User_123" }
71
+
72
+ // Example 9: MapOr - map or return default
73
+ const mapOrSome = Option.Some(5).mapOr(0, (x) => x * 2)
74
+ console.log("9. mapOr on Some:", mapOrSome) // 10
75
+
76
+ const mapOrNone = Option.None.mapOr(0, (x) => x * 2)
77
+ console.log(" mapOr on None:", mapOrNone) // 0
78
+
79
+ // Example 10: Chaining map with different transformations
80
+ const chained = Option.Some(" hello world ")
81
+ .map((s) => s.trim())
82
+ .map((s) => s.toUpperCase())
83
+ .map((s) => s.split(" "))
84
+ .map((arr) => arr.join("-"))
85
+ console.log("10. Chain transformations:", chained.unwrap()) // "HELLO-WORLD"
86
+
87
+ // Example 11: Using map for safe property access
88
+ type Person = { name: string; age?: number }
89
+ const person = Option.Some<Person>({ name: "Alice", age: 30 })
90
+ const ageDoubled = person
91
+ .map((p) => p.age)
92
+ .map((age) => age ?? 0)
93
+ .map((age) => age * 2)
94
+ console.log("11. Safe property access:", ageDoubled.unwrap()) // 60
95
+
96
+ // Example 12: Map with None from nullable
97
+ const fromNull = Option.fromNullable(null)
98
+ const mappedNull = fromNull.map((x) => x * 2)
99
+ console.log("12. Map from null:", mappedNull.toString()) // Option::None
100
+
101
+ // Example 13: Map with filter-like behavior
102
+ const numbers2 = Option.Some([1, 2, 3, 4, 5])
103
+ const filteredSum = numbers2.map((arr) => {
104
+ const filtered = arr.filter((x) => x > 2)
105
+ return filtered.reduce((sum, x) => sum + x, 0)
106
+ })
107
+ console.log("13. Filter-like map:", filteredSum.unwrap()) // 12 (3 + 4 + 5)
108
+
109
+ console.log("\n=== All map examples completed ===")