@carbonteq/fp 0.5.4 → 0.7.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -0
  3. package/dist/chunk-7QVYU63E.js +7 -0
  4. package/dist/chunk-7QVYU63E.js.map +1 -0
  5. package/dist/index.cjs +46 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +4 -0
  8. package/dist/index.d.ts +4 -0
  9. package/dist/index.js +16 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/match.cjs +43 -0
  12. package/dist/match.cjs.map +1 -0
  13. package/dist/match.d.cts +14 -0
  14. package/dist/match.d.ts +14 -0
  15. package/dist/match.js +20 -0
  16. package/dist/match.js.map +1 -0
  17. package/dist/option.cjs +227 -0
  18. package/dist/option.cjs.map +1 -0
  19. package/dist/option.d.cts +58 -0
  20. package/dist/option.d.ts +58 -0
  21. package/dist/option.js +204 -0
  22. package/dist/option.js.map +1 -0
  23. package/dist/result.cjs +288 -0
  24. package/dist/result.cjs.map +1 -0
  25. package/dist/result.d.cts +150 -0
  26. package/{lib → dist}/result.d.ts +52 -24
  27. package/dist/result.js +264 -0
  28. package/dist/result.js.map +1 -0
  29. package/dist/tuple.cjs +41 -0
  30. package/dist/tuple.cjs.map +1 -0
  31. package/dist/tuple.d.cts +9 -0
  32. package/dist/tuple.d.ts +9 -0
  33. package/dist/tuple.js +18 -0
  34. package/dist/tuple.js.map +1 -0
  35. package/dist/unit.cjs +29 -0
  36. package/dist/unit.cjs.map +1 -0
  37. package/dist/unit.d.cts +4 -0
  38. package/dist/unit.d.ts +4 -0
  39. package/dist/unit.js +6 -0
  40. package/dist/unit.js.map +1 -0
  41. package/package.json +65 -72
  42. package/lib/index.d.ts +0 -7
  43. package/lib/index.d.ts.map +0 -1
  44. package/lib/index.js +0 -1
  45. package/lib/index.mjs +0 -1
  46. package/lib/match.d.ts +0 -11
  47. package/lib/match.d.ts.map +0 -1
  48. package/lib/option.d.ts +0 -43
  49. package/lib/option.d.ts.map +0 -1
  50. package/lib/result.d.ts.map +0 -1
  51. package/lib/unit.d.ts +0 -3
  52. package/lib/unit.d.ts.map +0 -1
@@ -0,0 +1,150 @@
1
+ import { UNIT } from './unit.cjs';
2
+
3
+ declare class UnwrappedErrWithOk extends Error {
4
+ constructor(r: Result<unknown, unknown>);
5
+ }
6
+ declare class UnwrappedOkWithErr extends Error {
7
+ constructor(r: Result<unknown, unknown>);
8
+ }
9
+ type UnitResult<E = never> = Result<UNIT, E>;
10
+ type Mapper<T, U> = (val: T) => U;
11
+ type AsyncMapper<T, U> = (val: T) => Promise<U>;
12
+ type OkOrErr = "ok" | "err";
13
+ type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
14
+ ok: U;
15
+ err: E;
16
+ } : never;
17
+ type CombinedResultOk<T extends Result<unknown, unknown>[]> = {
18
+ [K in keyof T]: UnwrapResult<T[K]>["ok"];
19
+ };
20
+ type CombinedResultErr<T extends Result<unknown, unknown>[]> = {
21
+ [K in keyof T]: UnwrapResult<T[K]>["err"];
22
+ }[number];
23
+ type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
24
+ type InnerMapMapper<T, U> = T extends Array<infer Inner> ? (val: Inner) => U : never;
25
+ type InnerMapReturn<T, E, U> = T extends Array<unknown> ? Result<Array<U>, E> : never;
26
+ /** Sentinel value */
27
+ declare const Sentinel: unique symbol;
28
+ type Sentinel = typeof Sentinel;
29
+ declare class Result<T, E> {
30
+ private readonly val;
31
+ private readonly error;
32
+ static readonly UNIT_RESULT: UnitResult;
33
+ protected constructor(val: T | Sentinel, error: E | Sentinel);
34
+ static Ok<T, E = never>(val: T): Result<T, E>;
35
+ static Err<E, T = never>(err: E): Result<T, E>;
36
+ isOk(): this is Result<T, never>;
37
+ isErr(): this is Result<never, E>;
38
+ isUnit(): this is Result<UNIT, never>;
39
+ toString(): string;
40
+ unwrap(): T;
41
+ unwrapOr(def: T): T;
42
+ unwrapOrElse(def: () => T): T;
43
+ unwrapOrElse(def: () => Promise<T>): Promise<T>;
44
+ safeUnwrap(): T | null;
45
+ unwrapErr(): E;
46
+ safeUnwrapErr(): E | null;
47
+ /**
48
+ *
49
+ * @param {Mapper<T, U>} fn The mapping/endofunctor to apply to the internal Ok value (T -> U)
50
+ * @returns Result<U, E> containing the mapped value
51
+ * @example
52
+ * const r = Result.Ok({data: 42})
53
+ * const r2 = Result.Err(new Error("something went wrong"))
54
+ * const mapper = (d: {data: 42}) => d.data * 2
55
+ * const result1 = r.map(mapper) // Result containing 64 as the ok value
56
+ * const result2 = r2.map(mapper) // mapper won't be applied, as r2 was in error state
57
+ */
58
+ map<U>(fn: (val: T) => Promise<U>): Promise<Result<U, E>>;
59
+ map<U>(fn: (val: T) => U): Result<U, E>;
60
+ /** Same as map, but for the error value instead of the Ok value */
61
+ mapErr<U>(fn: Mapper<E, U>): Result<T, U>;
62
+ mapOr<U>(default_: U, fn: Mapper<T, U>): U;
63
+ mapOrAsync<U>(default_: U, fn: AsyncMapper<T, U>): Promise<U>;
64
+ /** For combining two results. For the lazy eval version, see {@link flatZip} and {@link zipAsync} */
65
+ and<U, E2>(r: Result<U, E2>): Result<[T, U], E | E2>;
66
+ /**
67
+ * Also known as `andThen`, `bind` or `fmap`
68
+ * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value
69
+ * @example
70
+ * const r: Result<string, SomeError> = Result.Ok("42")
71
+ * const mapper = (d: string) => {
72
+ * const n = Number.parseInt(d)
73
+ * if(Number.isNumber(n) && !Number.isNaN(n)) return Result.Ok(n)
74
+ *
75
+ * return Result.Err(new InvalidNumStringError(d))
76
+ * }
77
+ * const result1 = r.map(mapper) // Type is Result<Result<number, InvalidNumStringError>, SomeError>
78
+ * const result2 = r.flatMap(mapper) // Type is Result<number, SomeError | InvalidNumStringError>
79
+ */
80
+ flatMap<U, E2>(fn: (val: T) => Promise<Result<U, E | E2>>): Promise<Result<U, E | E2>>;
81
+ flatMap<U, E2>(fn: (val: T) => Result<U, E2>): Result<U, E | E2>;
82
+ /**
83
+ * Also known as `andThen`, `fmap` or `flatMap`
84
+ * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value
85
+ * @example
86
+ * const r: Result<string, SomeError> = Result.Ok("42")
87
+ * const mapper = (d: string) => {
88
+ * const n = Number.parseInt(d)
89
+ * if(Number.isNumber(n) && !Number.isNaN(n)) return Result.Ok(n)
90
+ *
91
+ * return Result.Err(new InvalidNumStringError(d))
92
+ * }
93
+ * const result1 = r.map(mapper) // Type is Result<Result<number, InvalidNumStringError>, SomeError>
94
+ * const result2 = r.bind(mapper) // Type is Result<number, SomeError | InvalidNumStringError>
95
+ */
96
+ bind<U, E2>(fn: (val: T) => Promise<Result<U, E | E2>>): Promise<Result<U, E | E2>>;
97
+ bind<U, E2>(fn: (val: T) => Result<U, E2>): Result<U, E | E2>;
98
+ /**
99
+ * For combining the errors only while retaining the original value.
100
+ * @example
101
+ * const r: Result<string, SomeError> = Result.Ok('42')
102
+ * const binderOk = (d: string) => Result.Ok<number, SomeOtherError>(0909)
103
+ * const binderErr = (d: string) => Result.Err<number, SomeOtherError>(new SomeOtherError())
104
+ *
105
+ * const res1 = r.zipErr(binderOk) // Result<string, SomeError | SomeOtherError> - Value: Result.Ok('42') - No change in Ok type
106
+ * const res2 = r.zipErr(binderErr) // Result<string, SomeError | SomeOtherError> - Value: Result.Err(new SomeOtherError())
107
+ */
108
+ zipErr<E2>(fn: (val: T) => Promise<Result<unknown, E2>>): Promise<Result<T, E | E2>>;
109
+ zipErr<E2>(fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;
110
+ /** For running infallible side-effects on the contained value. Up to the programmer to ensure the underlying function doesn't fail */
111
+ tap(fn: (val: T) => void): Result<T, E>;
112
+ /**
113
+ * Async version of {@link tap}
114
+ * @see {@link tap}
115
+ */
116
+ tapAsync(fn: (val: T) => Promise<void>): Promise<Result<T, E>>;
117
+ zip<U>(fn: (val: T) => Promise<U>): Promise<Result<[T, U], E>>;
118
+ zip<U>(fn: (val: T) => U): Result<[T, U], E>;
119
+ /** For combining two results lazily. For the eager eval version, see {@link and} */
120
+ flatZip<U, E2>(fn: (val: T) => Promise<Result<U, E2>>): Promise<Result<[T, U], E | E2>>;
121
+ flatZip<U, E2>(fn: (val: T) => Result<U, E2>): Result<[T, U], E | E2>;
122
+ /** Type guard specifying all array results as Ok/Err */
123
+ static all<T, E extends Error>(c: "ok", seq: Result<T, E>[]): seq is Result<T, never>[];
124
+ static all<T, E extends Error>(c: "err", seq: Result<T, E>[]): seq is Result<never, E>[];
125
+ /** Whether any of the underlying results are Ok or Err */
126
+ static any<T, E extends Error>(c: OkOrErr, seq: Result<T, E>[]): boolean;
127
+ /**
128
+ * `Result.sequence(Result<T1, E1>, Result<T2, E2>, ...)` will return `Result<[T1, T2, ...], E1 | E2 | ...>`
129
+ * @example
130
+ * const r1 = Result.Ok<string, string>("abc")
131
+ * const r2 = Result.Ok<number, Error>(123)
132
+ * const r = Result.sequence(r1, r2) // r will be of type Result<[string, number], string | Error>
133
+ */
134
+ static sequence<T extends Result<unknown, unknown>[]>(...results: T): Result<CombinedResultOk<T>, CombinedResultErr<T>>;
135
+ /** Convert a Result of a Promise to the Promise of a Result */
136
+ static lift<T, E extends Error>(r: Result<Promise<T>, E>): Promise<Result<T, E>>;
137
+ innerMap<U>(mapper: InnerMapMapper<T, U>): InnerMapReturn<T, E, U>;
138
+ pipe<U>(fn: (val: T) => U): Result<U, E>;
139
+ pipe<U, V>(fn: (val: T) => U, fn2: (val: U) => V): Result<V, E>;
140
+ pipe<U, V, W>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W): Result<W, E>;
141
+ pipe<U, V, W, X>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X): Result<X, E>;
142
+ pipe<U, V, W, X, Y>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y): Result<Y, E>;
143
+ pipe<U, V, W, X, Y, Z>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z): Result<Z, E>;
144
+ pipe<U, V, W, X, Y, Z, A>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A): Result<A, E>;
145
+ pipe<U, V, W, X, Y, Z, A, B>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B): Result<B, E>;
146
+ pipe<U, V, W, X, Y, Z, A, B, C>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B, fn9: (val: B) => C): Result<C, E>;
147
+ pipe<U, V, W, X, Y, Z, A, B, C, D>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B, fn9: (val: B) => C, fn10: (val: C) => D): Result<D, E>;
148
+ }
149
+
150
+ export { type CombineResults, Result, type UnitResult, type UnwrapResult, UnwrappedErrWithOk, UnwrappedOkWithErr };
@@ -1,15 +1,16 @@
1
- import { UNIT } from "./unit";
2
- export declare class UnwrappedErrWithOk extends Error {
1
+ import { UNIT } from './unit.js';
2
+
3
+ declare class UnwrappedErrWithOk extends Error {
3
4
  constructor(r: Result<unknown, unknown>);
4
5
  }
5
- export declare class UnwrappedOkWithErr extends Error {
6
+ declare class UnwrappedOkWithErr extends Error {
6
7
  constructor(r: Result<unknown, unknown>);
7
8
  }
8
- export type UnitResult<E = never> = Result<UNIT, E>;
9
+ type UnitResult<E = never> = Result<UNIT, E>;
9
10
  type Mapper<T, U> = (val: T) => U;
10
11
  type AsyncMapper<T, U> = (val: T) => Promise<U>;
11
12
  type OkOrErr = "ok" | "err";
12
- export type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
13
+ type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
13
14
  ok: U;
14
15
  err: E;
15
16
  } : never;
@@ -19,13 +20,13 @@ type CombinedResultOk<T extends Result<unknown, unknown>[]> = {
19
20
  type CombinedResultErr<T extends Result<unknown, unknown>[]> = {
20
21
  [K in keyof T]: UnwrapResult<T[K]>["err"];
21
22
  }[number];
22
- export type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
23
+ type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
23
24
  type InnerMapMapper<T, U> = T extends Array<infer Inner> ? (val: Inner) => U : never;
24
25
  type InnerMapReturn<T, E, U> = T extends Array<unknown> ? Result<Array<U>, E> : never;
25
26
  /** Sentinel value */
26
27
  declare const Sentinel: unique symbol;
27
28
  type Sentinel = typeof Sentinel;
28
- export declare class Result<T, E> {
29
+ declare class Result<T, E> {
29
30
  private readonly val;
30
31
  private readonly error;
31
32
  static readonly UNIT_RESULT: UnitResult;
@@ -34,6 +35,7 @@ export declare class Result<T, E> {
34
35
  static Err<E, T = never>(err: E): Result<T, E>;
35
36
  isOk(): this is Result<T, never>;
36
37
  isErr(): this is Result<never, E>;
38
+ isUnit(): this is Result<UNIT, never>;
37
39
  toString(): string;
38
40
  unwrap(): T;
39
41
  unwrapOr(def: T): T;
@@ -44,7 +46,7 @@ export declare class Result<T, E> {
44
46
  safeUnwrapErr(): E | null;
45
47
  /**
46
48
  *
47
- * @param {Mapper<T, U>} f The mapping/endofunctor to apply to the internal Ok value (T -> U)
49
+ * @param {Mapper<T, U>} fn The mapping/endofunctor to apply to the internal Ok value (T -> U)
48
50
  * @returns Result<U, E> containing the mapped value
49
51
  * @example
50
52
  * const r = Result.Ok({data: 42})
@@ -59,10 +61,26 @@ export declare class Result<T, E> {
59
61
  mapErr<U>(fn: Mapper<E, U>): Result<T, U>;
60
62
  mapOr<U>(default_: U, fn: Mapper<T, U>): U;
61
63
  mapOrAsync<U>(default_: U, fn: AsyncMapper<T, U>): Promise<U>;
62
- /** For combining two results. For the lazy eval version, see {@link zip} and {@link zipAsync} */
64
+ /** For combining two results. For the lazy eval version, see {@link flatZip} and {@link zipAsync} */
63
65
  and<U, E2>(r: Result<U, E2>): Result<[T, U], E | E2>;
64
66
  /**
65
- * Also known as `andThen` or `fmap`
67
+ * Also known as `andThen`, `bind` or `fmap`
68
+ * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value
69
+ * @example
70
+ * const r: Result<string, SomeError> = Result.Ok("42")
71
+ * const mapper = (d: string) => {
72
+ * const n = Number.parseInt(d)
73
+ * if(Number.isNumber(n) && !Number.isNaN(n)) return Result.Ok(n)
74
+ *
75
+ * return Result.Err(new InvalidNumStringError(d))
76
+ * }
77
+ * const result1 = r.map(mapper) // Type is Result<Result<number, InvalidNumStringError>, SomeError>
78
+ * const result2 = r.flatMap(mapper) // Type is Result<number, SomeError | InvalidNumStringError>
79
+ */
80
+ flatMap<U, E2>(fn: (val: T) => Promise<Result<U, E | E2>>): Promise<Result<U, E | E2>>;
81
+ flatMap<U, E2>(fn: (val: T) => Result<U, E2>): Result<U, E | E2>;
82
+ /**
83
+ * Also known as `andThen`, `fmap` or `flatMap`
66
84
  * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value
67
85
  * @example
68
86
  * const r: Result<string, SomeError> = Result.Ok("42")
@@ -84,23 +102,23 @@ export declare class Result<T, E> {
84
102
  * const binderOk = (d: string) => Result.Ok<number, SomeOtherError>(0909)
85
103
  * const binderErr = (d: string) => Result.Err<number, SomeOtherError>(new SomeOtherError())
86
104
  *
87
- * const res1 = r.bindErr(binderOk) // Result<string, SomeError | SomeOtherError> - Value: Result.Ok('42') - No change in Ok type
88
- * const res2 = r.bindErr(binderErr) // Result<string, SomeError | SomeOtherError> - Value: Result.Err(new SomeOtherError())
105
+ * const res1 = r.zipErr(binderOk) // Result<string, SomeError | SomeOtherError> - Value: Result.Ok('42') - No change in Ok type
106
+ * const res2 = r.zipErr(binderErr) // Result<string, SomeError | SomeOtherError> - Value: Result.Err(new SomeOtherError())
89
107
  */
90
- bindErr<E2>(fn: (val: T) => Promise<Result<unknown, E2>>): Promise<Result<T, E | E2>>;
91
- bindErr<E2>(fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;
108
+ zipErr<E2>(fn: (val: T) => Promise<Result<unknown, E2>>): Promise<Result<T, E | E2>>;
109
+ zipErr<E2>(fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;
92
110
  /** For running infallible side-effects on the contained value. Up to the programmer to ensure the underlying function doesn't fail */
93
- do(fn: (val: T) => void): Result<T, E>;
111
+ tap(fn: (val: T) => void): Result<T, E>;
94
112
  /**
95
- * Async version of {@link do}
96
- * @see {@link do}
113
+ * Async version of {@link tap}
114
+ * @see {@link tap}
97
115
  */
98
- doAsync(fn: (val: T) => Promise<void>): Promise<Result<T, E>>;
99
- combine<U>(fn: (val: T) => Promise<U>): Promise<Result<[T, U], E>>;
100
- combine<U>(fn: (val: T) => U): Result<[T, U], E>;
116
+ tapAsync(fn: (val: T) => Promise<void>): Promise<Result<T, E>>;
117
+ zip<U>(fn: (val: T) => Promise<U>): Promise<Result<[T, U], E>>;
118
+ zip<U>(fn: (val: T) => U): Result<[T, U], E>;
101
119
  /** For combining two results lazily. For the eager eval version, see {@link and} */
102
- zip<U, E2>(fn: (val: T) => Promise<Result<U, E2>>): Promise<Result<[T, U], E | E2>>;
103
- zip<U, E2>(fn: (val: T) => Result<U, E2>): Result<[T, U], E | E2>;
120
+ flatZip<U, E2>(fn: (val: T) => Promise<Result<U, E2>>): Promise<Result<[T, U], E | E2>>;
121
+ flatZip<U, E2>(fn: (val: T) => Result<U, E2>): Result<[T, U], E | E2>;
104
122
  /** Type guard specifying all array results as Ok/Err */
105
123
  static all<T, E extends Error>(c: "ok", seq: Result<T, E>[]): seq is Result<T, never>[];
106
124
  static all<T, E extends Error>(c: "err", seq: Result<T, E>[]): seq is Result<never, E>[];
@@ -117,6 +135,16 @@ export declare class Result<T, E> {
117
135
  /** Convert a Result of a Promise to the Promise of a Result */
118
136
  static lift<T, E extends Error>(r: Result<Promise<T>, E>): Promise<Result<T, E>>;
119
137
  innerMap<U>(mapper: InnerMapMapper<T, U>): InnerMapReturn<T, E, U>;
138
+ pipe<U>(fn: (val: T) => U): Result<U, E>;
139
+ pipe<U, V>(fn: (val: T) => U, fn2: (val: U) => V): Result<V, E>;
140
+ pipe<U, V, W>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W): Result<W, E>;
141
+ pipe<U, V, W, X>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X): Result<X, E>;
142
+ pipe<U, V, W, X, Y>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y): Result<Y, E>;
143
+ pipe<U, V, W, X, Y, Z>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z): Result<Z, E>;
144
+ pipe<U, V, W, X, Y, Z, A>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A): Result<A, E>;
145
+ pipe<U, V, W, X, Y, Z, A, B>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B): Result<B, E>;
146
+ pipe<U, V, W, X, Y, Z, A, B, C>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B, fn9: (val: B) => C): Result<C, E>;
147
+ pipe<U, V, W, X, Y, Z, A, B, C, D>(fn: (val: T) => U, fn2: (val: U) => V, fn3: (val: V) => W, fn4: (val: W) => X, fn5: (val: X) => Y, fn6: (val: Y) => Z, fn7: (val: Z) => A, fn8: (val: A) => B, fn9: (val: B) => C, fn10: (val: C) => D): Result<D, E>;
120
148
  }
121
- export {};
122
- //# sourceMappingURL=result.d.ts.map
149
+
150
+ export { type CombineResults, Result, type UnitResult, type UnwrapResult, UnwrappedErrWithOk, UnwrappedOkWithErr };
package/dist/result.js ADDED
@@ -0,0 +1,264 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+ import { isPromise } from "node:util/types";
5
+ import { UNIT } from "./unit.js";
6
+ class UnwrappedErrWithOk extends Error {
7
+ static {
8
+ __name(this, "UnwrappedErrWithOk");
9
+ }
10
+ constructor(r) {
11
+ super(`Attempted to call unwrapErr on an okay value: <${r}>`);
12
+ }
13
+ }
14
+ class UnwrappedOkWithErr extends Error {
15
+ static {
16
+ __name(this, "UnwrappedOkWithErr");
17
+ }
18
+ constructor(r) {
19
+ super(`Attempted to call unwrap on an Err value: <${r}>`);
20
+ }
21
+ }
22
+ const okPred = /* @__PURE__ */ __name((el) => el.isOk(), "okPred");
23
+ const errPred = /* @__PURE__ */ __name((el) => el.isErr(), "errPred");
24
+ const preds = [
25
+ okPred,
26
+ errPred
27
+ ];
28
+ const Sentinel = Symbol.for("ResultSentinel");
29
+ class Result {
30
+ static {
31
+ __name(this, "Result");
32
+ }
33
+ val;
34
+ error;
35
+ static UNIT_RESULT = new Result(UNIT, null);
36
+ constructor(val, error) {
37
+ this.val = val;
38
+ this.error = error;
39
+ }
40
+ static Ok(val) {
41
+ return new Result(val, Sentinel);
42
+ }
43
+ static Err(err) {
44
+ return new Result(Sentinel, err);
45
+ }
46
+ isOk() {
47
+ return this.val !== Sentinel;
48
+ }
49
+ isErr() {
50
+ return this.error !== Sentinel;
51
+ }
52
+ isUnit() {
53
+ return this.val === UNIT;
54
+ }
55
+ toString() {
56
+ if (this.val !== Sentinel) {
57
+ return `Result::Ok<${this.val}>`;
58
+ }
59
+ return `Result::Err<${this.error}>`;
60
+ }
61
+ unwrap() {
62
+ if (this.val === Sentinel) {
63
+ if (this.error instanceof Error) throw this.error;
64
+ throw new UnwrappedOkWithErr(this);
65
+ }
66
+ return this.val;
67
+ }
68
+ unwrapOr(def) {
69
+ if (this.val === Sentinel) return def;
70
+ return this.val;
71
+ }
72
+ unwrapOrElse(def) {
73
+ if (this.val === Sentinel) return def();
74
+ return this.val;
75
+ }
76
+ safeUnwrap() {
77
+ return this.val === Sentinel ? null : this.val;
78
+ }
79
+ unwrapErr() {
80
+ if (this.isOk()) {
81
+ throw new UnwrappedErrWithOk(this);
82
+ }
83
+ return this.error;
84
+ }
85
+ safeUnwrapErr() {
86
+ return this.error === Sentinel ? null : this.error;
87
+ }
88
+ map(fn) {
89
+ if (this.val === Sentinel) return Result.Err(this.error);
90
+ const r = fn(this.val);
91
+ if (isPromise(r)) {
92
+ return r.then((val) => Result.Ok(val));
93
+ }
94
+ return Result.Ok(r);
95
+ }
96
+ /** Same as map, but for the error value instead of the Ok value */
97
+ mapErr(fn) {
98
+ if (this.error !== Sentinel) {
99
+ const mappedErr = fn(this.error);
100
+ return Result.Err(mappedErr);
101
+ }
102
+ return Result.Ok(this.val);
103
+ }
104
+ mapOr(default_, fn) {
105
+ if (this.val === Sentinel) return default_;
106
+ return fn(this.val);
107
+ }
108
+ mapOrAsync(default_, fn) {
109
+ if (this.val === Sentinel) return Promise.resolve(default_);
110
+ return fn(this.val);
111
+ }
112
+ /** For combining two results. For the lazy eval version, see {@link flatZip} and {@link zipAsync} */
113
+ and(r) {
114
+ if (this.isErr()) return this;
115
+ if (r.isErr()) return r;
116
+ return Result.Ok([
117
+ this.val,
118
+ r.val
119
+ ]);
120
+ }
121
+ flatMap(fn) {
122
+ if (this.val !== Sentinel) return fn(this.val);
123
+ return Result.Err(this.error);
124
+ }
125
+ bind(fn) {
126
+ if (this.val !== Sentinel) return fn(this.val);
127
+ return Result.Err(this.error);
128
+ }
129
+ zipErr(fn) {
130
+ if (this.val === Sentinel) return Result.Err(this.error);
131
+ const r = fn(this.val);
132
+ if (isPromise(r)) {
133
+ return r.then((result) => result.map((_) => this.val));
134
+ }
135
+ return r.map((_) => this.val);
136
+ }
137
+ /** For running infallible side-effects on the contained value. Up to the programmer to ensure the underlying function doesn't fail */
138
+ tap(fn) {
139
+ if (this.val !== Sentinel) {
140
+ fn(this.val);
141
+ }
142
+ return this;
143
+ }
144
+ /**
145
+ * Async version of {@link tap}
146
+ * @see {@link tap}
147
+ */
148
+ async tapAsync(fn) {
149
+ if (this.val !== Sentinel) {
150
+ await fn(this.val);
151
+ }
152
+ return this;
153
+ }
154
+ zip(fn) {
155
+ if (this.val === Sentinel) return Result.Err(this.error);
156
+ const r = fn(this.val);
157
+ if (isPromise(r)) {
158
+ return r.then((u) => Result.Ok([
159
+ this.val,
160
+ u
161
+ ]));
162
+ }
163
+ return Result.Ok([
164
+ this.val,
165
+ r
166
+ ]);
167
+ }
168
+ flatZip(fn) {
169
+ if (this.val === Sentinel) return Result.Err(this.error);
170
+ const r = fn(this.val);
171
+ if (isPromise(r)) {
172
+ return r.then((other) => other.map((u) => [
173
+ this.val,
174
+ u
175
+ ]));
176
+ }
177
+ return r.map((u) => [
178
+ this.val,
179
+ u
180
+ ]);
181
+ }
182
+ static all(c, seq) {
183
+ const pred = preds[Number(c === "ok")];
184
+ for (const el of seq) {
185
+ if (!pred(el)) return false;
186
+ }
187
+ return true;
188
+ }
189
+ /** Whether any of the underlying results are Ok or Err */
190
+ static any(c, seq) {
191
+ const pred = preds[Number(c === "ok")];
192
+ for (const el of seq) {
193
+ if (pred(el)) return true;
194
+ }
195
+ return false;
196
+ }
197
+ /**
198
+ * `Result.sequence(Result<T1, E1>, Result<T2, E2>, ...)` will return `Result<[T1, T2, ...], E1 | E2 | ...>`
199
+ * @example
200
+ * const r1 = Result.Ok<string, string>("abc")
201
+ * const r2 = Result.Ok<number, Error>(123)
202
+ * const r = Result.sequence(r1, r2) // r will be of type Result<[string, number], string | Error>
203
+ */
204
+ static sequence(...results) {
205
+ const vals = [];
206
+ for (const r of results) {
207
+ if (r.isErr()) return r;
208
+ vals.push(r.unwrap());
209
+ }
210
+ return Result.Ok(vals);
211
+ }
212
+ /** Convert a Result of a Promise to the Promise of a Result */
213
+ static async lift(r) {
214
+ if (r.isErr()) return Promise.resolve(Result.Err(r.error));
215
+ return r.val.then((v) => Result.Ok(v));
216
+ }
217
+ //#endregion
218
+ // static innerMap<T, U, E>(
219
+ // r: Result<Array<T>, E>,
220
+ // mapper: (val: T) => U,
221
+ // ): Result<Array<U>, E> {
222
+ // return r.map((inner) => inner.map(mapper));
223
+ // }
224
+ // innerMap<Inner, U>(
225
+ // this: Result<Array<Inner>, E>,
226
+ // mapper: (val: T) => U,
227
+ // ): Result<Array<U>, E>;
228
+ // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U): never;
229
+ // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U) {
230
+ // if (this.val === Sentinel) return this;
231
+ //
232
+ // if (Array.isArray(this.val)) {
233
+ // return Result.Ok(this.val.map(mapper));
234
+ // }
235
+ //
236
+ // throw new Error("Can only be called for Result<Array<T>, E>");
237
+ // }
238
+ innerMap(mapper) {
239
+ if (this.val === Sentinel) return this;
240
+ if (Array.isArray(this.val)) {
241
+ return Result.Ok(this.val.map(mapper));
242
+ }
243
+ throw new Error("Can only be called for Result<Array<T>, E>");
244
+ }
245
+ pipe(...fns) {
246
+ let res3 = this;
247
+ for (const fn of fns) {
248
+ res3 = res3.map(fn);
249
+ }
250
+ return res3;
251
+ }
252
+ }
253
+ const res = Result.Ok([
254
+ 1,
255
+ 2,
256
+ 3
257
+ ]);
258
+ const res2 = Result.Ok(123);
259
+ export {
260
+ Result,
261
+ UnwrappedErrWithOk,
262
+ UnwrappedOkWithErr
263
+ };
264
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/result.ts"],"sourcesContent":["import { isPromise } from \"node:util/types\";\nimport { UNIT } from \"./unit.js\";\n\nexport class UnwrappedErrWithOk extends Error {\n constructor(r: Result<unknown, unknown>) {\n super(`Attempted to call unwrapErr on an okay value: <${r}>`);\n }\n}\n\nexport class UnwrappedOkWithErr extends Error {\n constructor(r: Result<unknown, unknown>) {\n super(`Attempted to call unwrap on an Err value: <${r}>`);\n }\n}\n\nexport type UnitResult<E = never> = Result<UNIT, E>;\n\ntype Mapper<T, U> = (val: T) => U;\ntype AsyncMapper<T, U> = (val: T) => Promise<U>;\ntype ResMapper<T, U, E> = (val: T) => Result<U, E>;\ntype AsyncResMapper<T, U, E> = (val: T) => Promise<Result<U, E>>;\n\ntype OkOrErr = \"ok\" | \"err\";\nconst okPred = <T, E extends Error>(el: Result<T, E>): boolean => el.isOk();\nconst errPred = <T, E extends Error>(el: Result<T, E>): boolean => el.isErr();\nconst preds = [okPred, errPred];\n\nexport type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<\n infer U,\n infer E\n>\n ? { ok: U; err: E }\n : never;\n\ntype CombinedResultOk<T extends Result<unknown, unknown>[]> = {\n [K in keyof T]: UnwrapResult<T[K]>[\"ok\"];\n};\ntype CombinedResultErr<T extends Result<unknown, unknown>[]> = {\n [K in keyof T]: UnwrapResult<T[K]>[\"err\"];\n}[number];\n\nexport type CombineResults<T extends Result<unknown, unknown>[]> = Result<\n CombinedResultOk<T>,\n CombinedResultErr<T>\n>;\n\ntype InnerMapMapper<T, U> = T extends Array<infer Inner>\n ? (val: Inner) => U\n : never;\n\ntype InnerMapReturn<T, E, U> = T extends Array<unknown>\n ? Result<Array<U>, E>\n : never;\n\n/** Sentinel value */\nconst Sentinel = Symbol.for(\"ResultSentinel\");\ntype Sentinel = typeof Sentinel;\n\nexport class Result<T, E> {\n static readonly UNIT_RESULT: UnitResult = new Result(UNIT, null as never);\n\n protected constructor(\n private readonly val: T | Sentinel,\n private readonly error: E | Sentinel,\n ) {}\n\n static Ok<T, E = never>(val: T): Result<T, E> {\n return new Result(val, Sentinel) as Result<T, E>;\n }\n\n static Err<E, T = never>(err: E): Result<T, E> {\n return new Result(Sentinel, err) as Result<T, E>;\n }\n\n isOk(): this is Result<T, never> {\n return this.val !== Sentinel;\n }\n\n isErr(): this is Result<never, E> {\n return this.error !== Sentinel;\n }\n\n isUnit(): this is Result<UNIT, never> {\n return this.val === UNIT;\n }\n\n toString(): string {\n if (this.val !== Sentinel) {\n return `Result::Ok<${this.val}>`;\n }\n\n return `Result::Err<${this.error as E}>`;\n }\n\n unwrap(): T {\n if (this.val === Sentinel) {\n if (this.error instanceof Error) throw this.error;\n\n throw new UnwrappedOkWithErr(this);\n }\n\n return this.val;\n }\n\n unwrapOr(def: T): T {\n if (this.val === Sentinel) return def;\n\n return this.val;\n }\n\n unwrapOrElse(def: () => T): T;\n unwrapOrElse(def: () => Promise<T>): Promise<T>;\n unwrapOrElse(def: () => T | Promise<T>): T | Promise<T> {\n if (this.val === Sentinel) return def();\n\n return this.val;\n }\n\n safeUnwrap(): T | null {\n return this.val === Sentinel ? null : this.val;\n }\n\n unwrapErr(): E {\n if (this.isOk()) {\n throw new UnwrappedErrWithOk(this);\n }\n\n return this.error as E;\n }\n\n safeUnwrapErr(): E | null {\n return this.error === Sentinel ? null : this.error;\n }\n\n /**\n *\n * @param {Mapper<T, U>} fn The mapping/endofunctor to apply to the internal Ok value (T -> U)\n * @returns Result<U, E> containing the mapped value\n * @example\n * const r = Result.Ok({data: 42})\n * const r2 = Result.Err(new Error(\"something went wrong\"))\n * const mapper = (d: {data: 42}) => d.data * 2\n * const result1 = r.map(mapper) // Result containing 64 as the ok value\n * const result2 = r2.map(mapper) // mapper won't be applied, as r2 was in error state\n */\n map<U>(fn: (val: T) => Promise<U>): Promise<Result<U, E>>;\n map<U>(fn: (val: T) => U): Result<U, E>;\n map<U>(\n fn: Mapper<T, U> | AsyncMapper<T, U>,\n ): Result<U, E> | Promise<Result<U, E>> {\n if (this.val === Sentinel) return Result.Err(this.error) as Result<U, E>;\n\n const r = fn(this.val);\n\n if (isPromise(r)) {\n return r.then((val) => Result.Ok(val) as Result<U, E>);\n }\n\n return Result.Ok(r) as Result<U, E>;\n }\n\n /** Same as map, but for the error value instead of the Ok value */\n mapErr<U>(fn: Mapper<E, U>): Result<T, U> {\n if (this.error !== Sentinel) {\n const mappedErr = fn(this.error);\n\n return Result.Err(mappedErr);\n }\n\n return Result.Ok(this.val as T);\n }\n\n mapOr<U>(default_: U, fn: Mapper<T, U>): U {\n if (this.val === Sentinel) return default_;\n\n return fn(this.val);\n }\n\n mapOrAsync<U>(default_: U, fn: AsyncMapper<T, U>): Promise<U> {\n if (this.val === Sentinel) return Promise.resolve(default_);\n\n return fn(this.val);\n }\n\n /** For combining two results. For the lazy eval version, see {@link flatZip} and {@link zipAsync} */\n and<U, E2>(r: Result<U, E2>): Result<[T, U], E | E2> {\n if (this.isErr()) return this;\n\n // return r.map(v => [this.val, v] as [T, U])\n if (r.isErr()) return r;\n\n return Result.Ok([this.val, r.val] as [T, U]);\n }\n\n /**\n * Also known as `andThen`, `bind` or `fmap`\n * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value\n * @example\n * const r: Result<string, SomeError> = Result.Ok(\"42\")\n * const mapper = (d: string) => {\n * const n = Number.parseInt(d)\n * if(Number.isNumber(n) && !Number.isNaN(n)) return Result.Ok(n)\n *\n * return Result.Err(new InvalidNumStringError(d))\n * }\n * const result1 = r.map(mapper) // Type is Result<Result<number, InvalidNumStringError>, SomeError>\n * const result2 = r.flatMap(mapper) // Type is Result<number, SomeError | InvalidNumStringError>\n */\n flatMap<U, E2>(\n fn: (val: T) => Promise<Result<U, E | E2>>,\n ): Promise<Result<U, E | E2>>;\n flatMap<U, E2>(fn: (val: T) => Result<U, E2>): Result<U, E | E2>;\n flatMap<U, E2>(fn: ResMapper<T, U, E | E2> | AsyncResMapper<T, U, E | E2>) {\n if (this.val !== Sentinel) return fn(this.val);\n\n return Result.Err(this.error);\n }\n\n /**\n * Also known as `andThen`, `fmap` or `flatMap`\n * Like Result.map but used in cases where the mapper func returns a Result instead of a containable value\n * @example\n * const r: Result<string, SomeError> = Result.Ok(\"42\")\n * const mapper = (d: string) => {\n * const n = Number.parseInt(d)\n * if(Number.isNumber(n) && !Number.isNaN(n)) return Result.Ok(n)\n *\n * return Result.Err(new InvalidNumStringError(d))\n * }\n * const result1 = r.map(mapper) // Type is Result<Result<number, InvalidNumStringError>, SomeError>\n * const result2 = r.bind(mapper) // Type is Result<number, SomeError | InvalidNumStringError>\n */\n bind<U, E2>(\n fn: (val: T) => Promise<Result<U, E | E2>>,\n ): Promise<Result<U, E | E2>>;\n bind<U, E2>(fn: (val: T) => Result<U, E2>): Result<U, E | E2>;\n bind<U, E2>(fn: ResMapper<T, U, E | E2> | AsyncResMapper<T, U, E | E2>) {\n if (this.val !== Sentinel) return fn(this.val);\n\n return Result.Err(this.error);\n }\n\n /**\n * For combining the errors only while retaining the original value.\n * @example\n * const r: Result<string, SomeError> = Result.Ok('42')\n * const binderOk = (d: string) => Result.Ok<number, SomeOtherError>(0909)\n * const binderErr = (d: string) => Result.Err<number, SomeOtherError>(new SomeOtherError())\n *\n * const res1 = r.zipErr(binderOk) // Result<string, SomeError | SomeOtherError> - Value: Result.Ok('42') - No change in Ok type\n * const res2 = r.zipErr(binderErr) // Result<string, SomeError | SomeOtherError> - Value: Result.Err(new SomeOtherError())\n */\n zipErr<E2>(\n fn: (val: T) => Promise<Result<unknown, E2>>,\n ): Promise<Result<T, E | E2>>;\n zipErr<E2>(fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;\n zipErr<E2>(\n fn: ResMapper<T, unknown, E | E2> | AsyncResMapper<T, unknown, E | E2>,\n ) {\n if (this.val === Sentinel) return Result.Err(this.error);\n\n const r = fn(this.val);\n\n if (isPromise(r)) {\n return r.then((result) => result.map((_) => this.val));\n }\n\n return r.map((_) => this.val);\n }\n\n /** For running infallible side-effects on the contained value. Up to the programmer to ensure the underlying function doesn't fail */\n tap(fn: (val: T) => void): Result<T, E> {\n if (this.val !== Sentinel) {\n fn(this.val);\n }\n\n return this;\n }\n\n /**\n * Async version of {@link tap}\n * @see {@link tap}\n */\n async tapAsync(fn: (val: T) => Promise<void>): Promise<Result<T, E>> {\n if (this.val !== Sentinel) {\n await fn(this.val);\n }\n\n return this;\n }\n\n zip<U>(fn: (val: T) => Promise<U>): Promise<Result<[T, U], E>>;\n zip<U>(fn: (val: T) => U): Result<[T, U], E>;\n zip<U>(fn: Mapper<T, U> | AsyncMapper<T, U>) {\n if (this.val === Sentinel) return Result.Err(this.error);\n\n const r = fn(this.val);\n if (isPromise(r)) {\n return r.then((u) => Result.Ok([this.val, u]) as Result<[T, U], E>);\n }\n\n return Result.Ok([this.val, r]) as Result<[T, U], E>;\n }\n // zip<U>(fn: (val: T) => Promise<U>): Promise<Result<AppendToTuple<T, U>, E>>;\n // zip<U>(fn: (val: T) => U): Result<AppendToTuple<T, U>, E>;\n // zip<U>(fn: Mapper<T, U> | AsyncMapper<T, U>) {\n // \tif (this.val === Sentinel) return Result.Err(this.error);\n //\n // \ttype Tup = AppendToTuple<T, U>;\n // \tconst isTup = isTuple(this.val);\n //\n // \tconst r = fn(this.val);\n // \tif (isPromise(r)) {\n // \t\treturn r.then((u) => {\n // \t\t\tconst tuple: Tuple<Tup> = setAsTuple(\n // \t\t\t\t//@ts-expect-error\n // \t\t\t\tisTup ? [...this.val, u] : [this.val, u],\n // \t\t\t);\n //\n // \t\t\t//@ts-expect-error\n // \t\t\treturn Result.Ok(tuple) as Result<AppendToTuple<T, U>, E>;\n // \t\t});\n // \t}\n //\n // \tconst tuple: Tuple<Tup> = setAsTuple(\n // \t\t//@ts-expect-error\n // \t\tisTup ? [...this.val, r] : [this.val, r],\n // \t);\n //\n // \t//@ts-expect-error\n // \treturn Result.Ok(tuple) as Result<AppendToTuple<T, U>, E>;\n // }\n\n /** For combining two results lazily. For the eager eval version, see {@link and} */\n flatZip<U, E2>(\n fn: (val: T) => Promise<Result<U, E2>>,\n ): Promise<Result<[T, U], E | E2>>;\n flatZip<U, E2>(fn: (val: T) => Result<U, E2>): Result<[T, U], E | E2>;\n flatZip<U, E2>(fn: ResMapper<T, U, E | E2> | AsyncResMapper<T, U, E | E2>) {\n if (this.val === Sentinel) return Result.Err(this.error);\n\n const r = fn(this.val);\n if (isPromise(r)) {\n return r.then((other) => other.map((u) => [this.val, u]));\n }\n\n return r.map((u) => [this.val, u]);\n }\n // flatZip<U, E2>(\n // \tfn: (val: T) => Promise<Result<U, E2>>,\n // ): Promise<Result<AppendToTuple<T, U>, E | E2>>;\n // flatZip<U, E2>(\n // \tfn: (val: T) => Result<U, E2>,\n // ): Result<AppendToTuple<T, U>, E | E2>;\n // flatZip<U, E2>(fn: ResMapper<T, U, E | E2> | AsyncResMapper<T, U, E | E2>) {\n // \tif (this.val === Sentinel) return Result.Err(this.error);\n //\n // \ttype Tup = AppendToTuple<T, U>;\n // \tconst isTup = isTuple(this.val);\n //\n // \tconst r = fn(this.val);\n // \tif (isPromise(r)) {\n // \t\treturn r.then((other) =>\n // \t\t\tother.map((u) => (isTup ? [...this.val, u] : [this.val, u]) as Tup),\n // \t\t);\n // \t}\n //\n // \treturn r.map((u) => (isTup ? [...this.val, u] : [this.val, u]) as Tup);\n // }\n\n //#region General combo functions\n /** Type guard specifying all array results as Ok/Err */\n static all<T, E extends Error>(\n c: \"ok\",\n seq: Result<T, E>[],\n ): seq is Result<T, never>[];\n static all<T, E extends Error>(\n c: \"err\",\n seq: Result<T, E>[],\n ): seq is Result<never, E>[];\n static all<T, E extends Error>(c: OkOrErr, seq: Result<T, E>[]): boolean {\n const pred = preds[Number(c === \"ok\")];\n\n for (const el of seq) {\n if (!pred(el)) return false;\n }\n\n return true;\n }\n\n /** Whether any of the underlying results are Ok or Err */\n static any<T, E extends Error>(c: OkOrErr, seq: Result<T, E>[]): boolean {\n const pred = preds[Number(c === \"ok\")];\n\n for (const el of seq) {\n if (pred(el)) return true;\n }\n\n return false;\n }\n\n /**\n * `Result.sequence(Result<T1, E1>, Result<T2, E2>, ...)` will return `Result<[T1, T2, ...], E1 | E2 | ...>`\n * @example\n * const r1 = Result.Ok<string, string>(\"abc\")\n * const r2 = Result.Ok<number, Error>(123)\n * const r = Result.sequence(r1, r2) // r will be of type Result<[string, number], string | Error>\n */\n static sequence<T extends Result<unknown, unknown>[]>(\n ...results: T\n ): Result<CombinedResultOk<T>, CombinedResultErr<T>> {\n const vals = [] as CombinedResultOk<T>;\n\n for (const r of results) {\n if (r.isErr()) return r;\n\n vals.push(r.unwrap());\n }\n\n return Result.Ok(vals) as Result<CombinedResultOk<T>, CombinedResultErr<T>>;\n }\n\n /** Convert a Result of a Promise to the Promise of a Result */\n static async lift<T, E extends Error>(\n r: Result<Promise<T>, E>,\n ): Promise<Result<T, E>> {\n if (r.isErr()) return Promise.resolve(Result.Err(r.error as E));\n\n return (r.val as Promise<T>).then((v) => Result.Ok(v));\n }\n //#endregion\n\n // static innerMap<T, U, E>(\n // \tr: Result<Array<T>, E>,\n // \tmapper: (val: T) => U,\n // ): Result<Array<U>, E> {\n // \treturn r.map((inner) => inner.map(mapper));\n // }\n // innerMap<Inner, U>(\n // \tthis: Result<Array<Inner>, E>,\n // \tmapper: (val: T) => U,\n // ): Result<Array<U>, E>;\n // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U): never;\n // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U) {\n // \tif (this.val === Sentinel) return this;\n //\n // \tif (Array.isArray(this.val)) {\n // \t\treturn Result.Ok(this.val.map(mapper));\n // \t}\n //\n // \tthrow new Error(\"Can only be called for Result<Array<T>, E>\");\n // }\n\n innerMap<U>(mapper: InnerMapMapper<T, U>): InnerMapReturn<T, E, U> {\n type RetType = InnerMapReturn<T, E, U>;\n\n // @ts-expect-error\n if (this.val === Sentinel) return this;\n\n if (Array.isArray(this.val)) {\n return Result.Ok(this.val.map(mapper)) as RetType;\n }\n\n throw new Error(\"Can only be called for Result<Array<T>, E>\");\n }\n\n // @ts-expect-error\n pipe<U>(fn: (val: T) => U): Result<U, E>;\n pipe<U, V>(fn: (val: T) => U, fn2: (val: U) => V): Result<V, E>;\n pipe<U, V, W>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n ): Result<W, E>;\n pipe<U, V, W, X>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n ): Result<X, E>;\n pipe<U, V, W, X, Y>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n ): Result<Y, E>;\n pipe<U, V, W, X, Y, Z>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n fn6: (val: Y) => Z,\n ): Result<Z, E>;\n pipe<U, V, W, X, Y, Z, A>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n fn6: (val: Y) => Z,\n fn7: (val: Z) => A,\n ): Result<A, E>;\n pipe<U, V, W, X, Y, Z, A, B>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n fn6: (val: Y) => Z,\n fn7: (val: Z) => A,\n fn8: (val: A) => B,\n ): Result<B, E>;\n pipe<U, V, W, X, Y, Z, A, B, C>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n fn6: (val: Y) => Z,\n fn7: (val: Z) => A,\n fn8: (val: A) => B,\n fn9: (val: B) => C,\n ): Result<C, E>;\n pipe<U, V, W, X, Y, Z, A, B, C, D>(\n fn: (val: T) => U,\n fn2: (val: U) => V,\n fn3: (val: V) => W,\n fn4: (val: W) => X,\n fn5: (val: X) => Y,\n fn6: (val: Y) => Z,\n fn7: (val: Z) => A,\n fn8: (val: A) => B,\n fn9: (val: B) => C,\n fn10: (val: C) => D,\n ): Result<D, E>;\n pipe(...fns: Mapper<unknown, unknown>[]) {\n let res = this;\n for (const fn of fns) {\n // @ts-expect-error\n res = res.map(fn);\n }\n return res;\n }\n}\n\nconst res = Result.Ok([1, 2, 3]);\nconst res2 = Result.Ok(123);\n"],"mappings":";;;AAAA,SAASA,iBAAiB;AAC1B,SAASC,YAAY;AAEd,MAAMC,2BAA2BC,MAAAA;EAHxC,OAGwCA;;;EACtCC,YAAYC,GAA6B;AACvC,UAAM,kDAAkDA,CAAAA,GAAI;EAC9D;AACF;AAEO,MAAMC,2BAA2BH,MAAAA;EATxC,OASwCA;;;EACtCC,YAAYC,GAA6B;AACvC,UAAM,8CAA8CA,CAAAA,GAAI;EAC1D;AACF;AAUA,MAAME,SAAS,wBAAqBC,OAA8BA,GAAGC,KAAI,GAA1D;AACf,MAAMC,UAAU,wBAAqBF,OAA8BA,GAAGG,MAAK,GAA3D;AAChB,MAAMC,QAAQ;EAACL;EAAQG;;AA8BvB,MAAMG,WAAWC,OAAOC,IAAI,gBAAA;AAGrB,MAAMC,OAAAA;EA1Db,OA0DaA;;;;;EACX,OAAgBC,cAA0B,IAAID,OAAOf,MAAM,IAAA;EAE3D,YACmBiB,KACAC,OACjB;SAFiBD,MAAAA;SACAC,QAAAA;EAChB;EAEH,OAAOC,GAAiBF,KAAsB;AAC5C,WAAO,IAAIF,OAAOE,KAAKL,QAAAA;EACzB;EAEA,OAAOQ,IAAkBC,KAAsB;AAC7C,WAAO,IAAIN,OAAOH,UAAUS,GAAAA;EAC9B;EAEAb,OAAiC;AAC/B,WAAO,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QAAON;AAEtByD,WAAKC,KAAK1D,EAAEoB,OAAM,CAAA;IACpB;AAEA,WAAOT,OAAOI,GAAG0C,IAAAA;EACnB;;EAGA,aAAaE,KACX3D,GACuB;AACvB,QAAIA,EAAEM,MAAK,EAAI,QAAO6B,QAAQC,QAAQzB,OAAOK,IAAIhB,EAAEc,KAAK,CAAA;AAExD,WAAQd,EAAEa,IAAmBgB,KAAK,CAAC+B,MAAMjD,OAAOI,GAAG6C,CAAAA,CAAAA;EACrD;;;;;;;;;;;;;;;;;;;;;;EAwBAC,SAAYC,QAAuD;AAIjE,QAAI,KAAKjD,QAAQL,SAAU,QAAO;AAElC,QAAIuD,MAAMC,QAAQ,KAAKnD,GAAG,GAAG;AAC3B,aAAOF,OAAOI,GAAG,KAAKF,IAAIc,IAAImC,MAAAA,CAAAA;IAChC;AAEA,UAAM,IAAIhE,MAAM,4CAAA;EAClB;EAyEAmE,QAAQC,KAAiC;AACvC,QAAIC,OAAM;AACV,eAAWvC,MAAMsC,KAAK;AAEpBC,MAAAA,OAAMA,KAAIxC,IAAIC,EAAAA;IAChB;AACA,WAAOuC;EACT;AACF;AAEA,MAAMA,MAAMxD,OAAOI,GAAG;EAAC;EAAG;EAAG;CAAE;AAC/B,MAAMqD,OAAOzD,OAAOI,GAAG,GAAA;","names":["isPromise","UNIT","UnwrappedErrWithOk","Error","constructor","r","UnwrappedOkWithErr","okPred","el","isOk","errPred","isErr","preds","Sentinel","Symbol","for","Result","UNIT_RESULT","val","error","Ok","Err","err","isUnit","toString","unwrap","unwrapOr","def","unwrapOrElse","safeUnwrap","unwrapErr","safeUnwrapErr","map","fn","then","mapErr","mappedErr","mapOr","default_","mapOrAsync","Promise","resolve","and","flatMap","bind","zipErr","result","_","tap","tapAsync","zip","u","flatZip","other","all","c","seq","pred","Number","any","sequence","results","vals","push","lift","v","innerMap","mapper","Array","isArray","pipe","fns","res","res2"]}
package/dist/tuple.cjs ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var tuple_exports = {};
21
+ __export(tuple_exports, {
22
+ isTuple: () => isTuple,
23
+ setAsTuple: () => setAsTuple
24
+ });
25
+ module.exports = __toCommonJS(tuple_exports);
26
+ const TUPLE_KEY = Symbol.for("TUPLE");
27
+ const setAsTuple = /* @__PURE__ */ __name((arr) => {
28
+ const res = arr;
29
+ res[TUPLE_KEY] = true;
30
+ return res;
31
+ }, "setAsTuple");
32
+ const isTuple = /* @__PURE__ */ __name((t) => (
33
+ //@ts-expect-error
34
+ Object.hasOwn(t, TUPLE_KEY)
35
+ ), "isTuple");
36
+ // Annotate the CommonJS export names for ESM import in node:
37
+ 0 && (module.exports = {
38
+ isTuple,
39
+ setAsTuple
40
+ });
41
+ //# sourceMappingURL=tuple.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tuple.ts"],"sourcesContent":["const TUPLE_KEY = Symbol.for(\"TUPLE\");\n\nexport interface Tuple<Inner> extends Array<Inner> {\n [TUPLE_KEY]: boolean;\n}\n\nexport const setAsTuple = <Inner, T extends Array<Inner>>(\n arr: T,\n): Tuple<Inner> => {\n //@ts-expect-error\n const res = arr as Tuple<Inner>;\n\n res[TUPLE_KEY] = true;\n\n return res;\n};\n\nexport const isTuple = <Inner>(t: unknown): t is Tuple<Inner> =>\n //@ts-expect-error\n Object.hasOwn(t, TUPLE_KEY);\n\nexport type AppendToTuple<T, U> = T extends [...infer Rest, infer L]\n ? [...Rest, L, U]\n : [T, U];\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;;;;;;AAAA,MAAMA,YAAYC,OAAOC,IAAI,OAAA;AAMtB,MAAMC,aAAa,wBACxBC,QAAAA;AAGA,QAAMC,MAAMD;AAEZC,MAAIL,SAAAA,IAAa;AAEjB,SAAOK;AACT,GAT0B;AAWnB,MAAMC,UAAU,wBAAQC;;EAE7BC,OAAOC,OAAOF,GAAGP,SAAAA;GAFI;","names":["TUPLE_KEY","Symbol","for","setAsTuple","arr","res","isTuple","t","Object","hasOwn"]}