@carbonteq/fp 0.8.2 → 0.9.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.
Files changed (103) hide show
  1. package/README.md +460 -51
  2. package/dist/errors.cjs +19 -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/index.cjs +13 -7
  11. package/dist/index.d.cts +6 -5
  12. package/dist/index.d.mts +6 -0
  13. package/dist/index.mjs +7 -0
  14. package/dist/match.cjs +12 -3
  15. package/dist/match.cjs.map +1 -0
  16. package/dist/match.d.cts +15 -5
  17. package/dist/match.d.cts.map +1 -0
  18. package/dist/{match-COIWq-e8.d.cts → match.d.mts} +3 -6
  19. package/dist/match.d.mts.map +1 -0
  20. package/dist/match.mjs +11 -0
  21. package/dist/match.mjs.map +1 -0
  22. package/dist/option.cjs +279 -4
  23. package/dist/option.cjs.map +1 -0
  24. package/dist/option.d.cts +99 -3
  25. package/dist/option.d.cts.map +1 -0
  26. package/dist/option.d.mts +99 -0
  27. package/dist/option.d.mts.map +1 -0
  28. package/dist/option.mjs +279 -0
  29. package/dist/option.mjs.map +1 -0
  30. package/dist/result.cjs +484 -5
  31. package/dist/result.cjs.map +1 -0
  32. package/dist/result.d.cts +142 -3
  33. package/dist/result.d.cts.map +1 -0
  34. package/dist/result.d.mts +142 -0
  35. package/dist/result.d.mts.map +1 -0
  36. package/dist/result.mjs +480 -0
  37. package/dist/result.mjs.map +1 -0
  38. package/dist/tuple.cjs.map +1 -1
  39. package/dist/tuple.d.cts +0 -1
  40. package/dist/tuple.d.cts.map +1 -1
  41. package/dist/{tuple.d.ts → tuple.d.mts} +1 -2
  42. package/dist/tuple.d.mts.map +1 -0
  43. package/dist/{tuple.js → tuple.mjs} +1 -1
  44. package/dist/tuple.mjs.map +1 -0
  45. package/dist/unit.cjs +6 -2
  46. package/dist/unit.cjs.map +1 -0
  47. package/dist/unit.d.cts +6 -2
  48. package/dist/unit.d.cts.map +1 -0
  49. package/dist/{unit-D0y_qAUW.d.cts → unit.d.mts} +1 -4
  50. package/dist/unit.d.mts.map +1 -0
  51. package/dist/{unit-udy5j53P.js → unit.mjs} +1 -1
  52. package/dist/unit.mjs.map +1 -0
  53. package/dist/utils.cjs +9 -0
  54. package/dist/utils.cjs.map +1 -0
  55. package/dist/utils.d.cts +5 -0
  56. package/dist/utils.d.cts.map +1 -0
  57. package/dist/utils.d.mts +5 -0
  58. package/dist/utils.d.mts.map +1 -0
  59. package/dist/utils.mjs +8 -0
  60. package/dist/utils.mjs.map +1 -0
  61. package/package.json +86 -46
  62. package/dist/chunk-CUT6urMc.cjs +0 -30
  63. package/dist/index.d.ts +0 -5
  64. package/dist/index.js +0 -6
  65. package/dist/match-BQP0RNSk.js +0 -13
  66. package/dist/match-BQP0RNSk.js.map +0 -1
  67. package/dist/match-COIWq-e8.d.cts.map +0 -1
  68. package/dist/match-DXKW7ym5.d.ts +0 -18
  69. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  70. package/dist/match-DyAuOeqx.cjs +0 -25
  71. package/dist/match-DyAuOeqx.cjs.map +0 -1
  72. package/dist/match.d.ts +0 -5
  73. package/dist/match.js +0 -3
  74. package/dist/option-8_eiz02z.d.cts +0 -45
  75. package/dist/option-8_eiz02z.d.cts.map +0 -1
  76. package/dist/option-Be_DXVE6.js +0 -181
  77. package/dist/option-Be_DXVE6.js.map +0 -1
  78. package/dist/option-CoelyMEg.d.ts +0 -45
  79. package/dist/option-CoelyMEg.d.ts.map +0 -1
  80. package/dist/option-DHCdfOco.cjs +0 -193
  81. package/dist/option-DHCdfOco.cjs.map +0 -1
  82. package/dist/option.d.ts +0 -3
  83. package/dist/option.js +0 -4
  84. package/dist/result-CdGWA5IL.js +0 -318
  85. package/dist/result-CdGWA5IL.js.map +0 -1
  86. package/dist/result-DsVjSFnO.d.ts +0 -132
  87. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  88. package/dist/result-Dy_C5dC6.d.cts +0 -132
  89. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  90. package/dist/result-nuhyCRyu.cjs +0 -336
  91. package/dist/result-nuhyCRyu.cjs.map +0 -1
  92. package/dist/result.d.ts +0 -3
  93. package/dist/result.js +0 -4
  94. package/dist/tuple.d.ts.map +0 -1
  95. package/dist/tuple.js.map +0 -1
  96. package/dist/unit-CnjFzJN1.cjs +0 -12
  97. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  98. package/dist/unit-CoBLIJFc.d.ts +0 -9
  99. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  100. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  101. package/dist/unit-udy5j53P.js.map +0 -1
  102. package/dist/unit.d.ts +0 -2
  103. package/dist/unit.js +0 -3
package/README.md CHANGED
@@ -22,13 +22,13 @@ yarn add @carbonteq/fp
22
22
  bun add @carbonteq/fp
23
23
  ```
24
24
 
25
- # But why fp?
25
+ ## But why fp?
26
26
 
27
27
  In JavaScript and TypeScript, dealing with `null`, `undefined`, and errors can lead to verbose, error-prone code. `fp` introduces functional paradigms that make handling these cases cleaner and more reliable. By leveraging `fp`, you can reduce boilerplate, improve readability, and create more maintainable applications.
28
28
 
29
29
  To demonstrate the utility of `fp`, let us consider a use case where we need to retrieve a user's email and address.
30
30
 
31
- ### Without using the `fp` library
31
+ ## Without using the `fp` library
32
32
 
33
33
  ```typescript
34
34
  function getUserByEmail(user: { email?: string }): string | null {
@@ -83,7 +83,7 @@ matchOpt(res, {
83
83
  // Output: User test@test.com has address: Some Address
84
84
  ```
85
85
 
86
- # Table of Contents
86
+ ## Table of Contents
87
87
 
88
88
  - [Usage](#usage)
89
89
  - [The `Result` type](#the-result-type)
@@ -95,21 +95,17 @@ matchOpt(res, {
95
95
  - [flatZip](#flatzip)
96
96
  - [Comparison of map and zip](#comparison-of-map-flatmap-zip-and-flatzip)
97
97
  - [Some Other Useful Functions](#some-other-useful-functions)
98
- - [mapErr](#maperr)
99
- - [mapOr](#mapor) <!-- - [tap](#tap) -->
100
- - [all](#all)
101
- - [validate](#validate)
102
- - [unwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
103
- - [safeUnwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
104
- - [unwrapOr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
105
- - [unwrapOrElse](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
106
- - [safeUnwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
107
- - [unwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
98
+ - [Creating Values from Existing Data](#creating-values-from-existing-data)
99
+ - [Exception Handling](#exception-handling)
100
+ - [Transforming Inner Values](#transforming-inner-values)
101
+ - [Combining & Converting](#combining--converting)
102
+ - [Error Recovery & Side Effects](#error-recovery--side-effects)
103
+ - [Aggregation Helpers](#aggregation-helpers)
108
104
  - [Build Your First Pipeline](#build-your-first-pipeline)
109
105
  - [Synchronous Pipeline](#synchronous-pipeline)
110
106
  - [Asynchronous Pipeline](#asynchronous-pipeline)
111
107
 
112
- # Usage
108
+ ## Usage
113
109
 
114
110
  ## The `Result` type
115
111
 
@@ -137,7 +133,7 @@ const opt2: Option<number> = Option.None; // Contains no value (None)
137
133
 
138
134
  ## Cheatsheet
139
135
 
140
- #### `map`
136
+ ### `map`
141
137
 
142
138
  Transforms the `Some` or `Ok` value inside `Option` or `Result`.
143
139
 
@@ -217,7 +213,7 @@ console.log(await processUser("Alice", 30)); // Output: Result.Ok("User Alice sa
217
213
 
218
214
  #### `zip`
219
215
 
220
- Creates a tuple `[T, U]` where the second value `U` is _derived_ from the first value `T` using a function `f`.
216
+ Creates a tuple `[T, U]` where the second value `U` is *derived* from the first value `T` using a function `f`.
221
217
  For example, suppose we want to pair the product's original price `T` and discounted price `U`.
222
218
 
223
219
  ```typescript
@@ -356,40 +352,6 @@ console.log(await safeFindUserById(10)); // Some(User: 10)
356
352
  console.log(await safeFindUserById(0)); // Some(User not found)
357
353
  ```
358
354
 
359
- <!-- #### `tap`
360
-
361
- `tap` is used to perform side effects on the `Result`/`Option` value without altering its contents. It is useful for logging, auditing, debugging complex chains of operations etc.
362
-
363
- ```typescript
364
- import { Result } from "@carbonteq/fp";
365
-
366
- // Simulated database functions
367
- async function findUserById(userId: number): Promise<Result<Record<string, number>, string>> {
368
- // Simulate a database lookup
369
- await Promise.resolve(userId);
370
- if (userId === 0) {
371
- return Result.Err("User not found");
372
- }
373
- return Result.Ok({ id: userId, balance: 100 });
374
- }
375
-
376
- function updateBalance(user: Record<string, number>, amount: number): Result<Record<string, number>, string> {
377
- if (user.balance < amount) {
378
- return Result.Err("Insufficient funds");
379
- }
380
- return Result.Ok({ ...user, balance: user.balance - amount });
381
- }
382
-
383
- // Process withdrawal with logging
384
- const res = (await findUserById(1))
385
- .tap((user) => console.log(`[Audit] User found: ${user.id}`))
386
- .flatMap((user) => updateBalance(user, 10))
387
- .tap((updated) => console.log(`[Transaction] New balance: $${updated.balance}`))
388
- .mapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
389
-
390
- console.log(res); // Result.Ok({ id: 1, balance: 90 })
391
- ``` -->
392
-
393
355
  #### `all`
394
356
 
395
357
  `all` is used to combine an array of Results. If any errors exist they are accumulated, else the values are accumulated.
@@ -621,11 +583,458 @@ const errorResult = Result.Err(new Error("Something went wrong"));
621
583
  console.log(errorResult.unwrapErr()); // unwrapErr: Error: Something went wrong (Extracts the error from Result.Err, throwing an error if it's Ok)
622
584
  ```
623
585
 
586
+ ---
587
+
588
+ ### Creating Values from Existing Data
589
+
590
+ #### `Option.fromNullable`
591
+
592
+ Creates an `Option` from a value that might be `null` or `undefined`, returning `None` for those values.
593
+
594
+ ```typescript
595
+ import { Option } from "@carbonteq/fp";
596
+
597
+ function findUser(id: string): { name: string } | null {
598
+ return id === "1" ? { name: "Alice" } : null;
599
+ }
600
+
601
+ const user = Option.fromNullable(findUser("1"));
602
+ console.log(user); // Some({ name: "Alice" })
603
+
604
+ const missing = Option.fromNullable(findUser("999"));
605
+ console.log(missing); // None
606
+ ```
607
+
608
+ #### `Option.fromFalsy`
609
+
610
+ Creates an `Option` from a value, returning `None` for any falsy value (`false`, `0`, `""`, `null`, `undefined`).
611
+
612
+ ```typescript
613
+ import { Option } from "@carbonteq/fp";
614
+
615
+ const valid = Option.fromFalsy("hello");
616
+ console.log(valid); // Some("hello")
617
+
618
+ const empty = Option.fromFalsy("");
619
+ console.log(empty); // None
620
+
621
+ const zero = Option.fromFalsy(0);
622
+ console.log(zero); // None
623
+ ```
624
+
625
+ #### `Option.fromPredicate`
626
+
627
+ Creates an `Option` based on a predicate function - returns `Some` if the predicate returns `true`, else `None`.
628
+
629
+ ```typescript
630
+ import { Option } from "@carbonteq/fp";
631
+
632
+ const age = 25;
633
+ const adult = Option.fromPredicate(age, (a) => a >= 18);
634
+ console.log(adult); // Some(25)
635
+
636
+ const minor = Option.fromPredicate(15, (a) => a >= 18);
637
+ console.log(minor); // None
638
+ ```
639
+
640
+ #### `Result.fromNullable`
641
+
642
+ Creates a `Result` from a nullable value, returning `Err` with the provided error for `null` or `undefined`.
643
+
644
+ ```typescript
645
+ import { Result } from "@carbonteq/fp";
646
+
647
+ function getConfig(key: string): string | undefined {
648
+ return process.env[key];
649
+ }
650
+
651
+ const config = Result.fromNullable(getConfig("API_KEY"), "API_KEY not set");
652
+ console.log(config); // Ok("...") or Err("API_KEY not set")
653
+ ```
654
+
655
+ #### `Result.fromPredicate`
656
+
657
+ Creates a `Result` based on a predicate function - returns `Ok` with the value if the predicate returns `true`, else `Err` with the provided error.
658
+
659
+ ```typescript
660
+ import { Result } from "@carbonteq/fp";
661
+
662
+ const score = 85;
663
+ const passed = Result.fromPredicate(
664
+ score,
665
+ (s) => s >= 60,
666
+ "Score too low",
667
+ );
668
+ console.log(passed); // Ok(85)
669
+
670
+ const failed = Result.fromPredicate(45, (s) => s >= 60, "Score too low");
671
+ console.log(failed); // Err("Score too low")
672
+ ```
673
+
674
+ ---
675
+
676
+ ### Exception Handling
677
+
678
+ #### `Result.tryCatch`
679
+
680
+ Wraps a synchronous operation in a `Result`, catching any exceptions and converting them to `Err`.
681
+
682
+ ```typescript
683
+ import { Result } from "@carbonteq/fp";
684
+
685
+ function parseJson(json: string): Result<unknown, Error> {
686
+ return Result.tryCatch(
687
+ () => JSON.parse(json),
688
+ (e) => e instanceof Error ? e : new Error(String(e)),
689
+ );
690
+ }
691
+
692
+ console.log(parseJson('{"name":"Alice"}')); // Ok({ name: "Alice" })
693
+ console.log(parseJson("invalid json")); // Err(SyntaxError: ...)
694
+ ```
695
+
696
+ #### `Result.tryAsyncCatch`
697
+
698
+ Wraps an asynchronous operation in a `Result`, catching any exceptions and converting them to `Err`.
699
+
700
+ ```typescript
701
+ import { Result } from "@carbonteq/fp";
702
+
703
+ async function fetchUserData(id: string): Result<Promise<{ name: string }>, Error> {
704
+ return Result.tryAsyncCatch(
705
+ async () => {
706
+ const response = await fetch(`/api/users/${id}`);
707
+ return response.json();
708
+ },
709
+ (e) => e instanceof Error ? e : new Error(String(e)),
710
+ );
711
+ }
712
+
713
+ const user = await fetchUserData("123").toPromise();
714
+ console.log(user); // Ok({ name: "..." }) or Err(Error: ...)
715
+ ```
716
+
717
+ ---
718
+
719
+ ### Transforming Inner Values
720
+
721
+ #### `Option.filter`
722
+
723
+ Filters the value inside an `Option` based on a predicate, returning `None` if the predicate returns `false`.
724
+
725
+ ```typescript
726
+ import { Option } from "@carbonteq/fp";
727
+
728
+ const age = Option.Some(25);
729
+ const adult = age.filter((a) => a >= 18);
730
+ console.log(adult); // Some(25)
731
+
732
+ const minor = Option.Some(15).filter((a) => a >= 18);
733
+ console.log(minor); // None
734
+ ```
735
+
736
+ #### `Option.innerMap`
737
+
738
+ Transforms array elements inside an `Option<Array<T>>`.
739
+
740
+ ```typescript
741
+ import { Option } from "@carbonteq/fp";
742
+
743
+ const numbers = Option.Some([1, 2, 3, 4, 5]);
744
+ const doubled = numbers.innerMap((n) => n * 2);
745
+ console.log(doubled); // Some([2, 4, 6, 8, 10])
746
+ ```
747
+
748
+ #### `Result.innerMap`
749
+
750
+ Transforms array elements inside a `Result<Array<T>, E>`.
751
+
752
+ ```typescript
753
+ import { Result } from "@carbonteq/fp";
754
+
755
+ const numbers = Result.Ok([1, 2, 3, 4, 5]);
756
+ const squared = numbers.innerMap((n) => n * n);
757
+ console.log(squared); // Ok([1, 4, 9, 16, 25])
758
+ ```
759
+
760
+ #### `Result.mapBoth`
761
+
762
+ Transforms both the success value and the error value simultaneously.
763
+
764
+ ```typescript
765
+ import { Result } from "@carbonteq/fp";
766
+
767
+ const result = Result.Ok(42);
768
+ const decorated = result.mapBoth(
769
+ (val) => `Success: ${val}`,
770
+ (err) => `Error: ${err}`,
771
+ );
772
+ console.log(decorated); // Ok("Success: 42")
773
+
774
+ const error = Result.Err("Something failed");
775
+ const decoratedError = error.mapBoth(
776
+ (val) => `Success: ${val}`,
777
+ (err) => `Error: ${err}`,
778
+ );
779
+ console.log(decoratedError); // Err("Error: Something failed")
780
+ ```
781
+
782
+ ---
783
+
784
+ ### Combining & Converting
785
+
786
+ #### `Option.toResult`
787
+
788
+ Converts an `Option` to a `Result`, using the provided error for `None`.
789
+
790
+ ```typescript
791
+ import { Option } from "@carbonteq/fp";
792
+
793
+ const user = Option.Some({ name: "Alice" });
794
+ const userResult = user.toResult("User not found");
795
+ console.log(userResult); // Ok({ name: "Alice" })
796
+
797
+ const missing = Option.None.toResult("User not found");
798
+ console.log(missing); // Err("User not found")
799
+ ```
800
+
801
+ #### `Result.toOption`
802
+
803
+ Converts a `Result` to an `Option`, discarding error information.
804
+
805
+ ```typescript
806
+ import { Result } from "@carbonteq/fp";
807
+
808
+ const success = Result.Ok(42);
809
+ const opt = success.toOption();
810
+ console.log(opt); // Some(42)
811
+
812
+ const failure = Result.Err("Failed");
813
+ const optFromErr = failure.toOption();
814
+ console.log(optFromErr); // None
815
+ ```
816
+
817
+ #### `Option.fromPromise`
818
+
819
+ Wraps a `Promise<Option<T>>` as an `Option<Promise<T>>`, enabling async chaining.
820
+
821
+ ```typescript
822
+ import { Option } from "@carbonteq/fp";
823
+
824
+ async function fetchUser(id: string): Promise<Option<{ name: string }>> {
825
+ return id === "1" ? Option.Some({ name: "Alice" }) : Option.None;
826
+ }
827
+
828
+ const userOpt = Option.fromPromise(fetchUser("1"));
829
+ console.log(userOpt); // Some(Promise<{ name: "Alice" }>)
830
+ ```
831
+
832
+ #### `Result.fromPromise`
833
+
834
+ Wraps a `Promise<Result<T, E>>` as a `Result<Promise<T>, E>`, enabling async chaining.
835
+
836
+ ```typescript
837
+ import { Result } from "@carbonteq/fp";
838
+
839
+ async function fetchData(id: string): Promise<Result<string, Error>> {
840
+ return id === "1" ? Result.Ok("Data") : Result.Err(new Error("Not found"));
841
+ }
842
+
843
+ const dataRes = Result.fromPromise(fetchData("1"));
844
+ console.log(dataRes); // Ok(Promise<"Data">)
845
+ ```
846
+
847
+ #### `Result.zipErr`
848
+
849
+ Runs a validation/binding function on the Ok value that can produce a new error, while preserving the original Ok value. If the function returns an `Err`, that error is returned. If the initial result is already `Err`, it short-circuits and returns that error.
850
+
851
+ ```typescript
852
+ import { Result } from "@carbonteq/fp";
853
+
854
+ const checkPermissions = (userId: string) =>
855
+ Result.Ok(userId).zipErr((id) =>
856
+ id === "guest" ? Result.Err("Guest users have limited access") : Result.Ok(undefined)
857
+ );
858
+
859
+ const admin = checkPermissions("admin-123");
860
+ console.log(admin); // Ok("admin-123")
861
+
862
+ const guest = checkPermissions("guest");
863
+ console.log(guest); // Err("Guest users have limited access")
864
+
865
+ const okNoChange = Result.Ok("42").zipErr((id) => Result.Ok(id.length));
866
+ console.log(okNoChange); // Ok("42")
867
+
868
+ const alreadyFailed = Result.Err<string, string>("Network error")
869
+ .zipErr(() => Result.Err("Validation error"));
870
+ console.log(alreadyFailed); // Err("Network error") - short-circuits
871
+ ```
872
+
873
+ ##### `mapErr` vs `zipErr`
874
+
875
+ `mapErr` transforms the error value only; it never runs on `Ok`. `zipErr` runs a binder on the `Ok` value that can *introduce* a new error, while preserving the original `Ok` value on success.
876
+
877
+ ```typescript
878
+ import { Result } from "@carbonteq/fp";
879
+
880
+ const res = Result.Err<number, Error>(new Error("boom"))
881
+ .mapErr((e) => e.message);
882
+ console.log(res); // Err("boom")
883
+
884
+ const ok = Result.Ok("42").zipErr((value) =>
885
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
886
+ );
887
+ console.log(ok); // Ok("42")
888
+
889
+ const err = Result.Ok("0").zipErr((value) =>
890
+ value === "0" ? Result.Err("invalid") : Result.Ok(value.length)
891
+ );
892
+ console.log(err); // Err("invalid")
893
+ ```
894
+
895
+ #### `Result.flip`
896
+
897
+ Swaps the `Ok` and `Err` states, turning success into failure and vice versa.
898
+
899
+ ```typescript
900
+ import { Result } from "@carbonteq/fp";
901
+
902
+ const success = Result.Ok("Success value");
903
+ const flipped = success.flip();
904
+ console.log(flipped); // Err("Success value")
905
+
906
+ const failure = Result.Err("Error value");
907
+ const flippedError = failure.flip();
908
+ console.log(flippedError); // Ok("Error value")
909
+ ```
910
+
911
+ ---
912
+
913
+ ### Error Recovery & Side Effects
914
+
915
+ #### `tap`
916
+
917
+ Executes a side effect function for `Some` or `Ok` values, then returns the original `Option` or `Result`. Useful for logging, debugging, or executing effects without changing the value.
918
+
919
+ ```typescript
920
+ import { Result } from "@carbonteq/fp";
921
+
922
+ // Simulated database functions
923
+ async function findUserById(userId: number): Promise<Result<Record<string, number>, string>> {
924
+ // Simulate a database lookup
925
+ await Promise.resolve(userId);
926
+ if (userId === 0) {
927
+ return Result.Err("User not found");
928
+ }
929
+ return Result.Ok({ id: userId, balance: 100 });
930
+ }
931
+
932
+ function updateBalance(user: Record<string, number>, amount: number): Result<Record<string, number>, string> {
933
+ if (user.balance < amount) {
934
+ return Result.Err("Insufficient funds");
935
+ }
936
+ return Result.Ok({ ...user, balance: user.balance - amount });
937
+ }
938
+
939
+ // Process withdrawal with logging
940
+ const res = (await findUserById(1))
941
+ .tap((user) => console.log(`[Audit] User found: ${user.id}`))
942
+ .flatMap((user) => updateBalance(user, 10))
943
+ .tap((updated) => console.log(`[Transaction] New balance: $${updated.balance}`))
944
+ .tapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
945
+
946
+ console.log(res); // Result.Ok({ id: 1, balance: 90 })
947
+ ```
948
+
949
+ #### `Result.tapErr`
950
+
951
+ Executes a side effect function for `Err` values, then returns the original `Result`.
952
+
953
+ ```typescript
954
+ import { Result } from "@carbonteq/fp";
955
+
956
+ const result = Result.Err("Connection failed");
957
+ const logged = result.tapErr((err) => {
958
+ console.error(`[Error Log] ${new Date().toISOString()}: ${err}`);
959
+ });
960
+ console.log(logged); // Err("Connection failed")
961
+ // Output: [Error Log] 2025-01-07T...: Connection failed
962
+ ```
963
+
964
+ #### `Result.orElse`
965
+
966
+ Recovers from an error by providing a fallback `Result`. If the current result is `Err`, the function is called with the error to produce a new result.
967
+
968
+ ```typescript
969
+ import { Result } from "@carbonteq/fp";
970
+
971
+ function fetchFromCache(id: string): Result<string, Error> {
972
+ return id === "cached" ? Result.Ok("Cached data") : Result.Err(new Error("Not in cache"));
973
+ }
974
+
975
+ function fetchFromAPI(id: string): Result<string, Error> {
976
+ return id === "1" ? Result.Ok("API data") : Result.Err(new Error("Not found"));
977
+ }
978
+
979
+ const cached = fetchFromCache("cached").orElse((err) => fetchFromAPI("1"));
980
+ console.log(cached); // Ok("Cached data")
981
+
982
+ const fromAPI = fetchFromCache("123").orElse((err) => fetchFromAPI("1"));
983
+ console.log(fromAPI); // Ok("API data")
984
+
985
+ const failed = fetchFromCache("123").orElse((err) => fetchFromAPI("999"));
986
+ console.log(failed); // Err(Error: Not found)
987
+ ```
988
+
989
+ ---
990
+
991
+ ### Aggregation Helpers
992
+
993
+ #### `Option.any`
994
+
995
+ Returns the first `Some` from a list of `Option`s, or `None` if all are `None`.
996
+
997
+ ```typescript
998
+ import { Option } from "@carbonteq/fp";
999
+
1000
+ const first = Option.any(
1001
+ Option.None,
1002
+ Option.Some("First value"),
1003
+ Option.Some("Second value"),
1004
+ );
1005
+ console.log(first); // Some("First value")
1006
+
1007
+ const allNone = Option.any(Option.None, Option.None, Option.None);
1008
+ console.log(allNone); // None
1009
+ ```
1010
+
1011
+ #### `Result.any`
1012
+
1013
+ Returns the first `Ok` from a list of `Result`s, or collects all errors if all are `Err`.
1014
+
1015
+ ```typescript
1016
+ import { Result } from "@carbonteq/fp";
1017
+
1018
+ const firstSuccess = Result.any(
1019
+ Result.Err("Error 1"),
1020
+ Result.Ok("First success"),
1021
+ Result.Ok("Second success"),
1022
+ );
1023
+ console.log(firstSuccess); // Ok("First success")
1024
+
1025
+ const allErrors = Result.any(
1026
+ Result.Err("Error 1"),
1027
+ Result.Err("Error 2"),
1028
+ Result.Err("Error 3"),
1029
+ );
1030
+ console.log(allErrors); // Err(["Error 1", "Error 2", "Error 3"])
1031
+ ```
1032
+
624
1033
  ## Build Your First Pipeline
625
1034
 
626
1035
  Let's build a pipeline for processing an e-commerce order. This example demonstrates handling user input validation, inventory checks, and order processing.
627
1036
 
628
- #### Synchronous Pipeline
1037
+ ### Synchronous Pipeline
629
1038
 
630
1039
  ```typescript
631
1040
  import { Result, matchRes } from "@carbonteq/fp";
@@ -0,0 +1,19 @@
1
+
2
+ //#region src/errors.ts
3
+ var UnwrappedErrWithOk = class extends Error {
4
+ constructor(result) {
5
+ super(`Attempted to call unwrapErr on an Ok result: ${result}`);
6
+ this.name = "UnwrappedErrWithOk";
7
+ }
8
+ };
9
+ var UnwrappedOkWithErr = class extends Error {
10
+ constructor(result) {
11
+ super(`Attempted to call unwrap on an Err result: ${result}`);
12
+ this.name = "UnwrappedOkWithErr";
13
+ }
14
+ };
15
+
16
+ //#endregion
17
+ exports.UnwrappedErrWithOk = UnwrappedErrWithOk;
18
+ exports.UnwrappedOkWithErr = UnwrappedOkWithErr;
19
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["// Error classes\nexport class UnwrappedErrWithOk extends Error {\n constructor(result: string) {\n super(`Attempted to call unwrapErr on an Ok result: ${result}`);\n this.name = \"UnwrappedErrWithOk\";\n }\n}\n\nexport class UnwrappedOkWithErr extends Error {\n constructor(result: string) {\n super(`Attempted to call unwrap on an Err result: ${result}`);\n this.name = \"UnwrappedOkWithErr\";\n }\n}\n"],"mappings":";;AACA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,QAAgB;AAC1B,QAAM,gDAAgD,SAAS;AAC/D,OAAK,OAAO;;;AAIhB,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,QAAgB;AAC1B,QAAM,8CAA8C,SAAS;AAC7D,OAAK,OAAO"}
@@ -0,0 +1,10 @@
1
+ //#region src/errors.d.ts
2
+ declare class UnwrappedErrWithOk extends Error {
3
+ constructor(result: string);
4
+ }
5
+ declare class UnwrappedOkWithErr extends Error {
6
+ constructor(result: string);
7
+ }
8
+ //#endregion
9
+ export { UnwrappedErrWithOk, UnwrappedOkWithErr };
10
+ //# sourceMappingURL=errors.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.cts","names":[],"sources":["../src/errors.ts"],"sourcesContent":[],"mappings":";cACa,kBAAA,SAA2B,KAAA;EAA3B,WAAA,CAAA,MAAA,EAAA,MAAmB;AAOhC;cAAa,kBAAA,SAA2B,KAAA"}
@@ -0,0 +1,10 @@
1
+ //#region src/errors.d.ts
2
+ declare class UnwrappedErrWithOk extends Error {
3
+ constructor(result: string);
4
+ }
5
+ declare class UnwrappedOkWithErr extends Error {
6
+ constructor(result: string);
7
+ }
8
+ //#endregion
9
+ export { UnwrappedErrWithOk, UnwrappedOkWithErr };
10
+ //# sourceMappingURL=errors.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/errors.ts"],"sourcesContent":[],"mappings":";cACa,kBAAA,SAA2B,KAAA;EAA3B,WAAA,CAAA,MAAA,EAAA,MAAmB;AAOhC;cAAa,kBAAA,SAA2B,KAAA"}
@@ -0,0 +1,17 @@
1
+ //#region src/errors.ts
2
+ var UnwrappedErrWithOk = class extends Error {
3
+ constructor(result) {
4
+ super(`Attempted to call unwrapErr on an Ok result: ${result}`);
5
+ this.name = "UnwrappedErrWithOk";
6
+ }
7
+ };
8
+ var UnwrappedOkWithErr = class extends Error {
9
+ constructor(result) {
10
+ super(`Attempted to call unwrap on an Err result: ${result}`);
11
+ this.name = "UnwrappedOkWithErr";
12
+ }
13
+ };
14
+
15
+ //#endregion
16
+ export { UnwrappedErrWithOk, UnwrappedOkWithErr };
17
+ //# sourceMappingURL=errors.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["// Error classes\nexport class UnwrappedErrWithOk extends Error {\n constructor(result: string) {\n super(`Attempted to call unwrapErr on an Ok result: ${result}`);\n this.name = \"UnwrappedErrWithOk\";\n }\n}\n\nexport class UnwrappedOkWithErr extends Error {\n constructor(result: string) {\n super(`Attempted to call unwrap on an Err result: ${result}`);\n this.name = \"UnwrappedOkWithErr\";\n }\n}\n"],"mappings":";AACA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,QAAgB;AAC1B,QAAM,gDAAgD,SAAS;AAC/D,OAAK,OAAO;;;AAIhB,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,QAAgB;AAC1B,QAAM,8CAA8C,SAAS;AAC7D,OAAK,OAAO"}
package/dist/index.cjs CHANGED
@@ -1,13 +1,19 @@
1
- const require_unit = require('./unit-CnjFzJN1.cjs');
2
- const require_result = require('./result-nuhyCRyu.cjs');
3
- const require_option = require('./option-DHCdfOco.cjs');
4
- const require_match = require('./match-DyAuOeqx.cjs');
1
+ const require_errors = require('./errors.cjs');
2
+ const require_match = require('./match.cjs');
3
+ const require_unit = require('./unit.cjs');
4
+ const require_result = require('./result.cjs');
5
+ const require_option = require('./option.cjs');
5
6
 
6
7
  exports.Option = require_option.Option;
7
- exports.Result = require_result.Result;
8
+ Object.defineProperty(exports, 'Result', {
9
+ enumerable: true,
10
+ get: function () {
11
+ return require_result.Result;
12
+ }
13
+ });
8
14
  exports.UNIT = require_unit.UNIT;
9
- exports.UnwrappedErrWithOk = require_result.UnwrappedErrWithOk;
15
+ exports.UnwrappedErrWithOk = require_errors.UnwrappedErrWithOk;
10
16
  exports.UnwrappedNone = require_option.UnwrappedNone;
11
- exports.UnwrappedOkWithErr = require_result.UnwrappedOkWithErr;
17
+ exports.UnwrappedOkWithErr = require_errors.UnwrappedOkWithErr;
12
18
  exports.matchOpt = require_match.matchOpt;
13
19
  exports.matchRes = require_match.matchRes;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { UNIT } from "./unit-D0y_qAUW.cjs";
2
- import { CombineResults, Result, UnitResult, UnwrapResult, UnwrappedErrWithOk, UnwrappedOkWithErr } from "./result-Dy_C5dC6.cjs";
3
- import { Option, UnitOption, UnwrapOption, UnwrappedNone } from "./option-8_eiz02z.cjs";
4
- import { matchOpt, matchRes } from "./match-COIWq-e8.cjs";
5
- export { CombineResults, Option, Result, UNIT, UnitOption, UnitResult, UnwrapOption, UnwrapResult, UnwrappedErrWithOk, UnwrappedNone, UnwrappedOkWithErr, matchOpt, matchRes };
1
+ import { UnwrappedErrWithOk, UnwrappedOkWithErr } from "./errors.cjs";
2
+ import { UNIT } from "./unit.cjs";
3
+ import { CombineResults, Result, UnitResult, UnwrapResult } from "./result.cjs";
4
+ import { Option, UnitOption, UnwrapOption, UnwrappedNone } from "./option.cjs";
5
+ import { matchOpt, matchRes } from "./match.cjs";
6
+ export { type CombineResults, Option, Result, UNIT, type UnitOption, type UnitResult, type UnwrapOption, type UnwrapResult, UnwrappedErrWithOk, UnwrappedNone, UnwrappedOkWithErr, matchOpt, matchRes };