@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
@@ -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 ===")