@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,23 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
const zipDemo = Result.Ok(100).zip((price) => price * 0.9)
|
|
4
|
+
console.log("zip:", zipDemo.unwrap())
|
|
5
|
+
|
|
6
|
+
const fetchPrice = async (
|
|
7
|
+
productId: string,
|
|
8
|
+
): Promise<Result<number, string>> => {
|
|
9
|
+
await Promise.resolve(productId)
|
|
10
|
+
return productId === "sku-1" ? Result.Ok(120) : Result.Err("Unknown product")
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const fetchStock = async (price: number): Promise<Result<number, string>> => {
|
|
14
|
+
await Promise.resolve(price)
|
|
15
|
+
return price > 0 ? Result.Ok(42) : Result.Err("Invalid price")
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const combined = await Result.Ok("sku-1")
|
|
19
|
+
.flatMap(fetchPrice)
|
|
20
|
+
.flatZip(fetchStock)
|
|
21
|
+
.toPromise()
|
|
22
|
+
|
|
23
|
+
console.log("flatZip:", combined.unwrap())
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
const hasMinimumLength = (password: string): Result<boolean, Error> =>
|
|
4
|
+
password.length < 8
|
|
5
|
+
? Result.Err(new Error("Password must be at least 8 characters"))
|
|
6
|
+
: Result.Ok(true)
|
|
7
|
+
|
|
8
|
+
const hasSpecialCharacters = (password: string): Result<boolean, Error> => {
|
|
9
|
+
const specialCharsRegex = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/
|
|
10
|
+
return !specialCharsRegex.test(password)
|
|
11
|
+
? Result.Err(
|
|
12
|
+
new Error("Password must contain at least one special character"),
|
|
13
|
+
)
|
|
14
|
+
: Result.Ok(true)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const isNotSameAsPrevious = async (
|
|
18
|
+
password: string,
|
|
19
|
+
): Promise<Result<boolean, Error>> => {
|
|
20
|
+
await Promise.resolve()
|
|
21
|
+
return password === "password123!"
|
|
22
|
+
? Result.Err(
|
|
23
|
+
new Error("New password cannot be the same as previous password"),
|
|
24
|
+
)
|
|
25
|
+
: Result.Ok(true)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const validated = Result.Ok("password321!").validate([
|
|
29
|
+
hasMinimumLength,
|
|
30
|
+
hasSpecialCharacters,
|
|
31
|
+
])
|
|
32
|
+
console.log("validate ok:", validated.unwrap())
|
|
33
|
+
|
|
34
|
+
const validatedErrs = await Result.Ok("password123!")
|
|
35
|
+
.validate([hasMinimumLength, hasSpecialCharacters, isNotSameAsPrevious])
|
|
36
|
+
.toPromise()
|
|
37
|
+
console.log("validate errs:", validatedErrs.unwrapErr().length)
|
|
38
|
+
|
|
39
|
+
const user = Result.Ok("USER_ID")
|
|
40
|
+
const posts = user.map((id) => ({ id, title: "Hello" }))
|
|
41
|
+
const likes = user.map((id) => ({ id, count: 3 }))
|
|
42
|
+
|
|
43
|
+
const aggregated = Result.all(user, posts, likes)
|
|
44
|
+
console.log("all:", aggregated.unwrap())
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
const getConfig = (key: string): string | undefined =>
|
|
4
|
+
key === "API_KEY" ? "secret" : undefined
|
|
5
|
+
|
|
6
|
+
const config = Result.fromNullable(getConfig("API_KEY"), "API_KEY not set")
|
|
7
|
+
console.log("fromNullable:", config.unwrap())
|
|
8
|
+
|
|
9
|
+
const passed = Result.fromPredicate(85, (score) => score >= 60, "Score too low")
|
|
10
|
+
console.log("fromPredicate ok:", passed.unwrap())
|
|
11
|
+
|
|
12
|
+
const parseJson = (json: string): Result<unknown, Error> =>
|
|
13
|
+
Result.tryCatch(
|
|
14
|
+
() => JSON.parse(json),
|
|
15
|
+
(e) => (e instanceof Error ? e : new Error(String(e))),
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
console.log("tryCatch:", parseJson('{"name":"Alice"}').unwrap())
|
|
19
|
+
|
|
20
|
+
const fetchUserData = (id: string): Result<Promise<{ name: string }>, Error> =>
|
|
21
|
+
Result.tryAsyncCatch(
|
|
22
|
+
async () => {
|
|
23
|
+
await Promise.resolve(id)
|
|
24
|
+
return { name: "Test User" }
|
|
25
|
+
},
|
|
26
|
+
(e) => (e instanceof Error ? e : new Error(String(e))),
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
const asyncResult = await fetchUserData("123").unwrap()
|
|
30
|
+
console.log("tryAsyncCatch:", asyncResult.name)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Result } from "../../dist/result.mjs"
|
|
2
|
+
|
|
3
|
+
const checkPermissions = (userId: string) =>
|
|
4
|
+
Result.Ok(userId).zipErr((id) =>
|
|
5
|
+
id === "guest"
|
|
6
|
+
? Result.Err("Guest users have limited access")
|
|
7
|
+
: Result.Ok(undefined),
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
const admin = checkPermissions("admin-123")
|
|
11
|
+
const guest = checkPermissions("guest")
|
|
12
|
+
console.log("zipErr ok:", admin.unwrap())
|
|
13
|
+
console.log("zipErr err:", guest.unwrapErr())
|
|
14
|
+
|
|
15
|
+
const logged = Result.Ok(10)
|
|
16
|
+
.tap((value) => console.log("tap:", value))
|
|
17
|
+
.map((value) => value + 1)
|
|
18
|
+
.tapErr((error) => console.error("tapErr:", error))
|
|
19
|
+
|
|
20
|
+
console.log("tap result:", logged.unwrap())
|
|
21
|
+
|
|
22
|
+
const fallback = Result.Err("Not in cache").orElse(() => Result.Ok("API data"))
|
|
23
|
+
console.log("orElse:", fallback.unwrap())
|
|
24
|
+
|
|
25
|
+
const first = Result.any(
|
|
26
|
+
Result.Err("Error 1"),
|
|
27
|
+
Result.Ok("First success"),
|
|
28
|
+
Result.Ok("Second success"),
|
|
29
|
+
)
|
|
30
|
+
console.log("any:", first.unwrap())
|
|
31
|
+
|
|
32
|
+
const flipped = Result.Ok("Success value").flip()
|
|
33
|
+
console.log("flip:", flipped.unwrapErr())
|
|
34
|
+
|
|
35
|
+
const asOption = Result.Ok(42).toOption()
|
|
36
|
+
console.log("toOption:", asOption.unwrap())
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result Examples Index (Stable)
|
|
3
|
+
*
|
|
4
|
+
* These examples use the stable Result API.
|
|
5
|
+
* Run examples with:
|
|
6
|
+
* bun run examples/result/01-basics.ts
|
|
7
|
+
* bun run examples/result/02-map-flatMap.ts
|
|
8
|
+
* etc.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASICS (files 01-03)
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 01-basics.ts - Ok/Err fundamentals and matching
|
|
17
|
+
* Run: bun run examples/result/01-basics.ts
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 02-map-flatMap.ts - map and flatMap chains (sync + async)
|
|
22
|
+
* Run: bun run examples/result/02-map-flatMap.ts
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 03-zip-flatZip.ts - zip and flatZip composition
|
|
27
|
+
* Run: bun run examples/result/03-zip-flatZip.ts
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
// ============================================================================
|
|
31
|
+
// VALIDATION & CONSTRUCTORS (files 04-05)
|
|
32
|
+
// ============================================================================
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 04-validation.ts - validate, all, and async validators
|
|
36
|
+
* Run: bun run examples/result/04-validation.ts
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 05-constructors.ts - fromNullable, fromPredicate, tryCatch, tryAsyncCatch
|
|
41
|
+
* Run: bun run examples/result/05-constructors.ts
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
// ============================================================================
|
|
45
|
+
// UTILITIES (file 06)
|
|
46
|
+
// ============================================================================
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 06-utilities.ts - tap, tapErr, zipErr, any, flip, toOption, orElse
|
|
50
|
+
* Run: bun run examples/result/06-utilities.ts
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
export {}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.map() - Transform the success value
|
|
3
|
+
*
|
|
4
|
+
* map() applies a function to the Ok value, leaving Err unchanged.
|
|
5
|
+
* If the Result is Err, the mapper function is NOT called.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// BASIC MAP EXAMPLES
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
console.log("=== Result.map() Examples ===\n")
|
|
15
|
+
|
|
16
|
+
// Example 1: Simple number transformation
|
|
17
|
+
const numberOk = Result.Ok(5)
|
|
18
|
+
const doubled = numberOk.map((x) => x * 2)
|
|
19
|
+
console.log("1. Double 5:", doubled.unwrap()) // 10
|
|
20
|
+
|
|
21
|
+
// Example 2: Map on Err - mapper is NOT called
|
|
22
|
+
const numberErr = Result.Err<string, number>("something went wrong")
|
|
23
|
+
const doubledErr = numberErr.map((x) => {
|
|
24
|
+
console.log(" This will NOT be printed!")
|
|
25
|
+
return x * 2
|
|
26
|
+
})
|
|
27
|
+
console.log("2. Map on Err:", doubledErr.unwrapErr()) // "something went wrong"
|
|
28
|
+
|
|
29
|
+
// Example 3: Chaining multiple maps
|
|
30
|
+
const result = Result.Ok(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 = Result.Ok<UserId>(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 can fail (but doesn't affect Result)
|
|
45
|
+
const parsed = Result.Ok("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 = Result.Ok([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
|
+
console.log("\n=== All map examples completed ===")
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.flatMap() - Chain Result-returning functions
|
|
3
|
+
*
|
|
4
|
+
* flatMap() (also known as bind/chain) is used to sequence operations
|
|
5
|
+
* that can fail. If the first Result is Err, the subsequent function
|
|
6
|
+
* is NOT called and the error propagates.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC FLATMAP EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Result.flatMap() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Simple flatMap chain
|
|
18
|
+
const parseNumber = (str: string): Result<number, "parse_error"> => {
|
|
19
|
+
const num = Number(str)
|
|
20
|
+
return Number.isNaN(num) ? Result.Err("parse_error") : Result.Ok(num)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const validatePositive = (n: number): Result<number, "not_positive"> => {
|
|
24
|
+
return n > 0 ? Result.Ok(n) : Result.Err("not_positive")
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const result = parseNumber("42").flatMap((n) => validatePositive(n))
|
|
28
|
+
console.log("1. Valid chain:", result.unwrap()) // 42
|
|
29
|
+
|
|
30
|
+
// Example 2: Short-circuit on first error
|
|
31
|
+
const errorResult = parseNumber("invalid").flatMap((n) => validatePositive(n))
|
|
32
|
+
console.log("2. Parse error:", errorResult.unwrapErr()) // "parse_error"
|
|
33
|
+
|
|
34
|
+
// Example 3: Short-circuit on second error
|
|
35
|
+
const errorResult2 = parseNumber("-5").flatMap((n) => validatePositive(n))
|
|
36
|
+
console.log("3. Validation error:", errorResult2.unwrapErr()) // "not_positive"
|
|
37
|
+
|
|
38
|
+
// Example 4: Chaining multiple flatMaps
|
|
39
|
+
const divide = (a: number, b: number): Result<number, "division_error"> => {
|
|
40
|
+
return b !== 0 ? Result.Ok(a / b) : Result.Err("division_error")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const calculation = Result.Ok(100)
|
|
44
|
+
.flatMap((n) => divide(n, 2))
|
|
45
|
+
.flatMap((n) => divide(n, 5))
|
|
46
|
+
.flatMap((n) => validatePositive(n))
|
|
47
|
+
console.log("4. Chain calculations:", calculation.unwrap()) // 10
|
|
48
|
+
|
|
49
|
+
// Example 5: flatMap for fetching/looking up values
|
|
50
|
+
type UserId = number
|
|
51
|
+
type User = { id: UserId; name: string }
|
|
52
|
+
type PostId = number
|
|
53
|
+
type Post = { id: PostId; authorId: UserId; title: string }
|
|
54
|
+
|
|
55
|
+
const users: Map<UserId, User> = new Map([
|
|
56
|
+
[1, { id: 1, name: "Alice" }],
|
|
57
|
+
[2, { id: 2, name: "Bob" }],
|
|
58
|
+
])
|
|
59
|
+
|
|
60
|
+
const posts: Map<PostId, Post> = new Map([
|
|
61
|
+
[101, { id: 101, authorId: 1, title: "Hello" }],
|
|
62
|
+
[102, { id: 102, authorId: 2, title: "World" }],
|
|
63
|
+
])
|
|
64
|
+
|
|
65
|
+
const getUser = (id: UserId): Result<User, "user_not_found"> => {
|
|
66
|
+
const user = users.get(id)
|
|
67
|
+
return user ? Result.Ok(user) : Result.Err("user_not_found")
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const getPost = (id: PostId): Result<Post, "post_not_found"> => {
|
|
71
|
+
const post = posts.get(id)
|
|
72
|
+
return post ? Result.Ok(post) : Result.Err("post_not_found")
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const getPostAuthor = (
|
|
76
|
+
postId: PostId,
|
|
77
|
+
): Result<User, "post_not_found" | "user_not_found"> => {
|
|
78
|
+
return getPost(postId).flatMap((post) => getUser(post.authorId))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
console.log("5. Get post author:", getPostAuthor(101).unwrap()) // { id: 1, name: "Alice" }
|
|
82
|
+
|
|
83
|
+
// Example 6: Error type union (errors accumulate)
|
|
84
|
+
const resultWithUnionError = parseNumber("invalid").flatMap((n) =>
|
|
85
|
+
validatePositive(n),
|
|
86
|
+
)
|
|
87
|
+
// Type is Result<number, "parse_error" | "not_positive">
|
|
88
|
+
console.log("6. Union error type:", resultWithUnionError.unwrapErr()) // "parse_error"
|
|
89
|
+
|
|
90
|
+
// Example 7: flatMap is synchronous - for async operations, use gen.async* methods
|
|
91
|
+
// See 07-asyncGen.ts and 08-asyncGenAdapter.ts for async patterns
|
|
92
|
+
|
|
93
|
+
// Example 8: Using flatMap for validation pipeline
|
|
94
|
+
type ValidationError = { field: string; message: string }
|
|
95
|
+
|
|
96
|
+
const requireString = (value: unknown): Result<string, ValidationError> => {
|
|
97
|
+
return typeof value === "string"
|
|
98
|
+
? Result.Ok(value)
|
|
99
|
+
: Result.Err({ field: "value", message: "Must be a string" })
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const requireNonEmpty = (str: string): Result<string, ValidationError> => {
|
|
103
|
+
return str.length > 0
|
|
104
|
+
? Result.Ok(str)
|
|
105
|
+
: Result.Err({ field: "value", message: "Cannot be empty" })
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const validateInput = (value: unknown): Result<string, ValidationError> => {
|
|
109
|
+
return requireString(value).flatMap((str) => requireNonEmpty(str))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
console.log("8. Valid input:", validateInput("hello").unwrap()) // "hello"
|
|
113
|
+
console.log(" Invalid input:", validateInput(123).unwrapErr()) // { field: "value", message: "Must be a string" }
|
|
114
|
+
|
|
115
|
+
// Example 9: flatMap vs map - when to use which
|
|
116
|
+
const mapExample = Result.Ok(5).map((x) => Result.Ok(x * 2)) // Result<Result<number, never>, never>
|
|
117
|
+
const flatMapExample = Result.Ok(5).flatMap((x) => Result.Ok(x * 2)) // Result<number, never>
|
|
118
|
+
|
|
119
|
+
console.log("9. map wraps Result:", mapExample.unwrap().unwrap()) // 10 (need double unwrap)
|
|
120
|
+
console.log(" flatMap flattens:", flatMapExample.unwrap()) // 10 (single unwrap)
|
|
121
|
+
|
|
122
|
+
// Example 10: Practical - User registration flow
|
|
123
|
+
type Email = string
|
|
124
|
+
type Password = string
|
|
125
|
+
type UserId2 = number
|
|
126
|
+
|
|
127
|
+
const validateEmail = (email: string): Result<Email, ValidationError> => {
|
|
128
|
+
return email.includes("@")
|
|
129
|
+
? Result.Ok(email)
|
|
130
|
+
: Result.Err({ field: "email", message: "Invalid email" })
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const validatePassword = (
|
|
134
|
+
password: string,
|
|
135
|
+
): Result<Password, ValidationError> => {
|
|
136
|
+
return password.length >= 8
|
|
137
|
+
? Result.Ok(password)
|
|
138
|
+
: Result.Err({ field: "password", message: "Password too short" })
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const createUser = (
|
|
142
|
+
_email: Email,
|
|
143
|
+
_password: Password,
|
|
144
|
+
): Result<UserId2, ValidationError> => {
|
|
145
|
+
// Simulate user creation
|
|
146
|
+
return Result.Ok(Math.floor(Math.random() * 1000))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const registerUser = (
|
|
150
|
+
email: string,
|
|
151
|
+
password: string,
|
|
152
|
+
): Result<UserId2, ValidationError> => {
|
|
153
|
+
return validateEmail(email).flatMap((validEmail) =>
|
|
154
|
+
validatePassword(password).flatMap((validPassword) =>
|
|
155
|
+
createUser(validEmail, validPassword),
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
console.log(
|
|
161
|
+
"10. Register valid user:",
|
|
162
|
+
registerUser("user@example.com", "password123")._tag,
|
|
163
|
+
) // "Ok"
|
|
164
|
+
console.log(
|
|
165
|
+
" Register invalid email:",
|
|
166
|
+
registerUser("invalid", "password123").unwrapErr(),
|
|
167
|
+
) // { field: "email", message: "Invalid email" }
|
|
168
|
+
|
|
169
|
+
console.log("\n=== All flatMap examples completed ===")
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result.zip() - Pair original value with derived value
|
|
3
|
+
*
|
|
4
|
+
* zip() takes a function that receives the current value and returns a new value.
|
|
5
|
+
* It returns a Result containing a tuple [original, derived].
|
|
6
|
+
* Useful when you need both the original and transformed values.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
|
|
10
|
+
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// BASIC ZIP EXAMPLES
|
|
13
|
+
// ============================================================================
|
|
14
|
+
|
|
15
|
+
console.log("=== Result.zip() Examples ===\n")
|
|
16
|
+
|
|
17
|
+
// Example 1: Basic zip - pair value with its double
|
|
18
|
+
const zipped = Result.Ok(5).zip((x) => x * 2)
|
|
19
|
+
console.log("1. Zip 5 with double:", zipped.unwrap()) // [5, 10]
|
|
20
|
+
|
|
21
|
+
// Example 2: Zip on Err - error propagates
|
|
22
|
+
const zippedErr = Result.Err<string, number>("error").zip((x) => x * 2)
|
|
23
|
+
console.log("2. Zip on Err:", zippedErr.unwrapErr()) // "error"
|
|
24
|
+
|
|
25
|
+
// Example 3: Zip is synchronous - for async operations, use gen.async* methods
|
|
26
|
+
// See 07-asyncGen.ts and 08-asyncGenAdapter.ts for async patterns
|
|
27
|
+
|
|
28
|
+
// Example 4: Zip for validation with context
|
|
29
|
+
const parseAndValidate = (str: string) => {
|
|
30
|
+
return Result.tryCatch(
|
|
31
|
+
() => parseInt(str, 10),
|
|
32
|
+
() => ({ error: "parse_failed" }),
|
|
33
|
+
)
|
|
34
|
+
.zip((num) => (num > 0 ? num : Result.Err("not_positive")))
|
|
35
|
+
.map(([original, _validated]) => ({
|
|
36
|
+
original: str,
|
|
37
|
+
parsed: original,
|
|
38
|
+
isValidated: true,
|
|
39
|
+
}))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
console.log("4. Parse with context:", parseAndValidate("42").unwrap()) // { original: "42", parsed: 42, isValidated: true }
|
|
43
|
+
|
|
44
|
+
// Example 5: Multiple zips - accumulate related values
|
|
45
|
+
const userStats = Result.Ok(100) // starting score
|
|
46
|
+
.zip((score) => score * 2) // double
|
|
47
|
+
.zip(([original, doubled]) => original + doubled) // sum
|
|
48
|
+
|
|
49
|
+
console.log("5. Multiple zips:", userStats.unwrap()) // [[100, 200], 300]
|
|
50
|
+
|
|
51
|
+
// Example 6: Zip for keeping audit trail
|
|
52
|
+
type Input = { value: number }
|
|
53
|
+
type Output = { result: number }
|
|
54
|
+
type WithAudit<T> = { input: Input; output: T }
|
|
55
|
+
|
|
56
|
+
const processWithAudit = (input: Input): Result<WithAudit<Output>, never> => {
|
|
57
|
+
return Result.Ok(input)
|
|
58
|
+
.zip((input) => ({ result: input.value * 2 }))
|
|
59
|
+
.map(([input, output]) => ({ input, output }))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
console.log("6. Process with audit:", processWithAudit({ value: 5 }).unwrap()) // { input: { value: 5 }, output: { result: 10 } }
|
|
63
|
+
|
|
64
|
+
// Example 7: Zip for before/after comparison
|
|
65
|
+
const beforeAndAfter = Result.Ok([1, 2, 3, 4, 5])
|
|
66
|
+
.zip((arr) => arr.filter((x) => x % 2 === 0))
|
|
67
|
+
.map(([original, filtered]) => ({
|
|
68
|
+
original,
|
|
69
|
+
filtered,
|
|
70
|
+
count: { original: original.length, filtered: filtered.length },
|
|
71
|
+
}))
|
|
72
|
+
|
|
73
|
+
console.log("7. Before/after:", beforeAndAfter.unwrap()) // { original: [1,2,3,4,5], filtered: [2,4], count: { original: 5, filtered: 2 } }
|
|
74
|
+
|
|
75
|
+
// Example 8: Zip for error context (preserve original on error)
|
|
76
|
+
// Note: zip doesn't do this directly, but shows the pattern
|
|
77
|
+
type ValidationError = { value: number; reason: string }
|
|
78
|
+
|
|
79
|
+
const safeDivide = (a: number, b: number): Result<number, ValidationError> => {
|
|
80
|
+
return b !== 0
|
|
81
|
+
? Result.Ok(a / b)
|
|
82
|
+
: Result.Err({ value: b, reason: "Division by zero" })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const divideWithContext = (
|
|
86
|
+
a: number,
|
|
87
|
+
b: number,
|
|
88
|
+
): Result<
|
|
89
|
+
{ dividend: number; divisor: number; quotient: number },
|
|
90
|
+
ValidationError
|
|
91
|
+
> => {
|
|
92
|
+
return Result.Ok({ dividend: a, divisor: b })
|
|
93
|
+
.flatZip(({ divisor }) => safeDivide(a, divisor))
|
|
94
|
+
.map(([context, quotient]) => ({ ...context, quotient }))
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
console.log("8. Divide with context:", divideWithContext(10, 2).unwrap()) // { dividend: 10, divisor: 2, quotient: 5 }
|
|
98
|
+
console.log(" Divide by zero:", divideWithContext(10, 0).unwrapErr()) // { value: 0, reason: "Division by zero" }
|
|
99
|
+
|
|
100
|
+
// Example 9: Zip for transformation history
|
|
101
|
+
type HistoryStep<T> = { step: number; value: T }
|
|
102
|
+
|
|
103
|
+
const withHistory = Result.Ok(5)
|
|
104
|
+
.zip((value) => value * 2)
|
|
105
|
+
.zip(([_original, doubled]) => doubled + 10)
|
|
106
|
+
.map(([[original, doubled], final]): HistoryStep<number>[] => [
|
|
107
|
+
{ step: 1, value: original },
|
|
108
|
+
{ step: 2, value: doubled },
|
|
109
|
+
{ step: 3, value: final },
|
|
110
|
+
])
|
|
111
|
+
|
|
112
|
+
console.log("9. Transformation history:", withHistory.unwrap()) // [{ step: 1, value: 5 }, { step: 2, value: 10 }, { step: 3, value: 20 }]
|
|
113
|
+
|
|
114
|
+
// Example 10: Practical - Form field validation with original value
|
|
115
|
+
type Field = { name: string; value: string }
|
|
116
|
+
type ValidatedField = { name: string; value: string; isValid: boolean }
|
|
117
|
+
|
|
118
|
+
const validateField = (field: Field): Result<ValidatedField, string> => {
|
|
119
|
+
return Result.Ok(field)
|
|
120
|
+
.flatZip((field) =>
|
|
121
|
+
field.value.length > 0
|
|
122
|
+
? Result.Ok(field)
|
|
123
|
+
: Result.Err(`${field.name} is empty`),
|
|
124
|
+
)
|
|
125
|
+
.map(([original, _]) => ({ ...original, isValid: true }))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
console.log(
|
|
129
|
+
"10. Valid field:",
|
|
130
|
+
validateField({ name: "email", value: "test@example.com" }).unwrap(),
|
|
131
|
+
) // { name: "email", value: "test@example.com", isValid: true }
|
|
132
|
+
console.log(
|
|
133
|
+
" Invalid field:",
|
|
134
|
+
validateField({ name: "email", value: "" }).unwrapErr(),
|
|
135
|
+
) // "email is empty"
|
|
136
|
+
|
|
137
|
+
// Example 11: Zip for accumulating calculations
|
|
138
|
+
const calculationSteps = Result.Ok(10)
|
|
139
|
+
.zip((n) => n + 5) // add
|
|
140
|
+
.zip(([_start, sum]) => sum * 2) // multiply
|
|
141
|
+
.zip(([[start, _sum], product]) => product - start) // subtract
|
|
142
|
+
|
|
143
|
+
console.log("11. Calculation steps:", calculationSteps.unwrap()) // [[[10, 15], 30], 20]
|
|
144
|
+
|
|
145
|
+
console.log("\n=== All zip examples completed ===")
|