@carbonteq/fp 0.9.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +326 -97
- package/dist/errors.cjs +2 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -5
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts +2 -5
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs +1 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +332 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +330 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +340 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +77 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +77 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +338 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +29 -14
- package/dist/index.d.cts +10 -5
- package/dist/index.d.mts +10 -5
- package/dist/index.mjs +10 -5
- package/dist/match.cjs +376 -3
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +467 -8
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +467 -8
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +371 -3
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1547 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1380 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1380 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1545 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +650 -71
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +528 -39
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +528 -39
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +648 -70
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1346 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1345 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +746 -81
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +799 -104
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +799 -104
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +742 -73
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +5 -4
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +9 -7
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +9 -7
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +4 -3
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +3 -3
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +4 -5
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +4 -5
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +2 -2
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +50 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +14 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +14 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +46 -3
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +60 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +240 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +244 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +154 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +157 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +54 -31
|
@@ -0,0 +1,157 @@
|
|
|
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 exactValueHandler = match(Result.Ok(42) as Result<number, string>)
|
|
62
|
+
.with(P.Ok(P.eq(42)), (value) => `exact:${value}`)
|
|
63
|
+
.with(P.Ok(), (value) => `other-ok:${value}`)
|
|
64
|
+
.with(P.Err(), (error) => `err:${String(error)}`)
|
|
65
|
+
.exhaustive()
|
|
66
|
+
console.log("exact value handler:", exactValueHandler)
|
|
67
|
+
|
|
68
|
+
const stateByPredicates = match(Option.None as Option<number>)
|
|
69
|
+
.when(P.IsSome, () => "some")
|
|
70
|
+
.when(P.IsNone, () => "none")
|
|
71
|
+
.otherwise(() => "other")
|
|
72
|
+
console.log("state by predicates:", stateByPredicates)
|
|
73
|
+
|
|
74
|
+
const combinedPredicates = match(Result.Ok(43) as Result<number, string>)
|
|
75
|
+
.with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
|
|
76
|
+
.with(P.Ok(), () => "miss")
|
|
77
|
+
.with(P.Err(), () => "err")
|
|
78
|
+
.exhaustive()
|
|
79
|
+
console.log("combined predicates:", combinedPredicates)
|
|
80
|
+
|
|
81
|
+
// -----------------------------------------------------------------------------
|
|
82
|
+
// 3) Generic discriminated unions
|
|
83
|
+
// -----------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
type PaymentState =
|
|
86
|
+
| { readonly _tag: "started"; id: string }
|
|
87
|
+
| { readonly _tag: "authorized"; id: string; amount: number }
|
|
88
|
+
| { readonly _tag: "declined"; id: string; reason: string }
|
|
89
|
+
|
|
90
|
+
const asPaymentState = (value: PaymentState): PaymentState => value
|
|
91
|
+
|
|
92
|
+
const payment = asPaymentState({
|
|
93
|
+
_tag: "authorized",
|
|
94
|
+
id: "pay-22",
|
|
95
|
+
amount: 199,
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
const paymentText = match(payment)
|
|
99
|
+
.with("started", (p) => `started:${p.id}`)
|
|
100
|
+
.with("authorized", (p) => `authorized:${p.id}:${p.amount}`)
|
|
101
|
+
.with("declined", (p) => `declined:${p.id}:${p.reason}`)
|
|
102
|
+
.exhaustive()
|
|
103
|
+
console.log("payment:", paymentText)
|
|
104
|
+
|
|
105
|
+
// -----------------------------------------------------------------------------
|
|
106
|
+
// 4) Async workflows with experimental types
|
|
107
|
+
// -----------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
async function loadQuota(id: number): Promise<Result<number, string>> {
|
|
110
|
+
return id > 0 ? Result.Ok(100 + id) : Result.Err("invalid-id")
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function runAsyncExamples(): Promise<void> {
|
|
114
|
+
// Preferred with experimental APIs:
|
|
115
|
+
// run async operations first (mapAsync/flatMapAsync/own async function),
|
|
116
|
+
// then match the settled ExperimentalResult/ExperimentalOption value.
|
|
117
|
+
|
|
118
|
+
const settledResult = await loadQuota(3)
|
|
119
|
+
const quotaText = match(settledResult)
|
|
120
|
+
.with("Ok", (quota) => `quota:${quota}`)
|
|
121
|
+
.with("Err", (error) => `quota-error:${error}`)
|
|
122
|
+
.exhaustive()
|
|
123
|
+
console.log("quota:", quotaText)
|
|
124
|
+
|
|
125
|
+
const settledOption = await Option.Some("admin").mapAsync(async (role) =>
|
|
126
|
+
role.toUpperCase(),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
const roleText = match(settledOption)
|
|
130
|
+
.with("Some", (role) => `role:${role}`)
|
|
131
|
+
.with("None", () => "role:none")
|
|
132
|
+
.exhaustive()
|
|
133
|
+
console.log("role:", roleText)
|
|
134
|
+
|
|
135
|
+
const rolePolicy = match(settledOption)
|
|
136
|
+
.with(P.Some(P.not(P.eq("ADMIN"))), (role) => `limited:${role}`)
|
|
137
|
+
.with(P.Some(P.eq("ADMIN")), () => "full-access")
|
|
138
|
+
.with(P.None(), () => "no-access")
|
|
139
|
+
.exhaustive()
|
|
140
|
+
console.log("role policy:", rolePolicy)
|
|
141
|
+
|
|
142
|
+
// You can still construct Result<Promise<T>, E> manually, but match() does not
|
|
143
|
+
// accept async-inner values directly. Settle first, then wrap/match.
|
|
144
|
+
const manualAsyncInner = Result.Ok(Promise.resolve(9))
|
|
145
|
+
const settledValue = await manualAsyncInner.unwrap()
|
|
146
|
+
const settledManual = Result.Ok(settledValue)
|
|
147
|
+
|
|
148
|
+
const manualText = match(settledManual)
|
|
149
|
+
.with("Ok", (value) => `manual:${value}`)
|
|
150
|
+
.with("Err", () => "manual:err")
|
|
151
|
+
.exhaustive()
|
|
152
|
+
console.log("manual async-inner settled:", manualText)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
await runAsyncExamples()
|
|
156
|
+
|
|
157
|
+
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 ===")
|