ok-fp 0.2.2 → 0.3.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.
@@ -1,142 +0,0 @@
1
- //#region src/either/either.ts
2
- function createEither(value) {
3
- const either = {
4
- filterOrElse: (predicate, onLeft) => either.flatMap((right) => predicate(right) ? either : createEither({ left: onLeft() })),
5
- map: (mapper) => either.flatMap((right) => createEither({ right: mapper(right) })),
6
- orElse: (fallback) => either.match((left) => forceCast(fallback(left)), () => forceCast(either)),
7
- ap: function(arg) {
8
- return this.flatMap((fn) => arg.map((right) => fn(right)));
9
- },
10
- swap: () => either.match((left) => createEither({ right: left }), (right) => createEither({ left: right })),
11
- zip: (eitherA) => either.map((value) => (a) => [value, a]).ap(eitherA),
12
- flatten: function() {
13
- return this.flatMap((value) => value);
14
- },
15
- flatMap: (mapper) => either.match(() => forceCast(either), (right) => forceCast(mapper(right))),
16
- tap: (sideEffect) => {
17
- either.match(() => {}, sideEffect);
18
- return either;
19
- },
20
- match: (onLeft, onRight) => isLeft(value) ? onLeft(value.left) : onRight(value.right),
21
- getOrElse: (fallback) => either.match((error) => fallback(error), (value) => value),
22
- toResult: () => either.match((error) => ({
23
- ok: false,
24
- error
25
- }), (value) => ({
26
- ok: true,
27
- value
28
- }))
29
- };
30
- return either;
31
- }
32
- function isLeft(value) {
33
- return typeof value === "object" && "left" in value;
34
- }
35
- function forceCast(either) {
36
- return either;
37
- }
38
-
39
- //#endregion
40
- //#region src/either/constructors.ts
41
- /**
42
- * Creates an Either containing an error value (Left).
43
- *
44
- * @typeParam E - The type of the error value
45
- * @typeParam T - The type of the success value (defaults to never since this is an error)
46
- * @param left - The error value to wrap
47
- * @returns Either containing the error value on the Left side
48
- *
49
- * @example
50
- * ```typescript
51
- * const error = left("Something went wrong"); // Either<string, never>
52
- * ```
53
- */
54
- function left(left) {
55
- return createEither({ left });
56
- }
57
- /**
58
- * Creates an Either containing a success value (Right).
59
- *
60
- * @typeParam T - The type of the success value
61
- * @typeParam E - The type of the error value (defaults to never since this is a success)
62
- * @param right - The success value to wrap
63
- * @returns Either containing the success value on the Right side
64
- *
65
- * @example
66
- * ```typescript
67
- * const success = right(42); // Either<never, number>
68
- * ```
69
- */
70
- function right(right) {
71
- return createEither({ right });
72
- }
73
- /**
74
- * Creates an Either from a potentially nullable value.
75
- * If the value is null or undefined, creates a Left with the provided error.
76
- * If the value is present, creates a Right with the value.
77
- *
78
- * @typeParam E - The type of the error value
79
- * @typeParam T - The type of the success value
80
- * @param nullable - The potentially null/undefined value
81
- * @param onNullish - Function that provides the error value when nullable is null/undefined
82
- * @returns Either containing the value if present, or the error if null/undefined
83
- *
84
- * @example
85
- * ```typescript
86
- * fromNullable("hello", () => "empty") // Right("hello")
87
- * fromNullable(null, () => "empty") // Left("empty")
88
- * fromNullable(undefined, () => "empty") // Left("empty")
89
- * ```
90
- */
91
- function fromNullable(nullable, onNullish) {
92
- return nullable != null ? right(nullable) : left(onNullish());
93
- }
94
- /**
95
- * Safely executes a function that might throw, converting exceptions to Either.
96
- *
97
- * @typeParam E - The type of the processed error value
98
- * @typeParam T - The type of the success value
99
- * @param fn - The function to execute that might throw
100
- * @param onThrow - Function that processes the caught error into the desired error type
101
- * @returns Either containing the result if successful, or the processed error if thrown
102
- *
103
- * @example
104
- * ```typescript
105
- * const parseNumber = (str: string) =>
106
- * tryCatch(
107
- * () => JSON.parse(str),
108
- * (err) => `Parse error: ${err.message}`
109
- * );
110
- *
111
- * parseNumber("42") // Right(42)
112
- * parseNumber("invalid") // Left("Parse error: ...")
113
- * ```
114
- */
115
- function tryCatch(fn, onThrow) {
116
- try {
117
- return right(fn());
118
- } catch (err) {
119
- return left(onThrow(err));
120
- }
121
- }
122
- /**
123
- * Creates an Either from an Option by providing an error value for the None case.
124
- *
125
- * @typeParam E - The type of the error value
126
- * @typeParam T - The type of the success value
127
- * @param opt - The Option to convert
128
- * @param onNone - Function that provides the error value when Option is None
129
- * @returns Either containing the Option's value if Some, or the error if None
130
- *
131
- * @example
132
- * ```typescript
133
- * fromOption(some(42), () => "empty") // Right(42)
134
- * fromOption(none(), () => "empty") // Left("empty")
135
- * ```
136
- */
137
- function fromOption(opt, onNone) {
138
- return opt.match(() => left(onNone()), (value) => right(value));
139
- }
140
-
141
- //#endregion
142
- export { tryCatch as a, right as i, fromOption as n, left as r, fromNullable as t };
@@ -1,213 +0,0 @@
1
- //#region src/either/model.d.ts
2
- type Left<E> = {
3
- readonly left: E;
4
- };
5
- type Right<T> = {
6
- readonly right: T;
7
- };
8
- type EitherValue<E, T> = Left<E> | Right<T>;
9
- type EitherResult<E, T> = {
10
- ok: true;
11
- value: T;
12
- } | {
13
- ok: false;
14
- error: E;
15
- };
16
- //#endregion
17
- //#region src/either/either.d.ts
18
- type Either<E, T> = {
19
- /**
20
- * Filters the Either based on a predicate function applied to the Right value.
21
- *
22
- * @param predicate - Function that tests the Right value
23
- * @param onLeft - Function that provides the error value when predicate fails
24
- * @returns The same Either if Left or predicate passes, otherwise Left with the provided error
25
- *
26
- * @example
27
- * ```typescript
28
- * const isPositive = (n: number) => n > 0;
29
- * right(5).filterOrElse(isPositive, () => "Must be positive") // Right(5)
30
- * right(-3).filterOrElse(isPositive, () => "Must be positive") // Left("Must be positive")
31
- * left("error").filterOrElse(isPositive, () => "Must be positive") // Left("error")
32
- * ```
33
- */
34
- filterOrElse: (predicate: (right: T) => boolean, onLeft: () => E) => Either<E, T>;
35
- /**
36
- * Transforms the Right value using a mapping function.
37
- *
38
- * @typeParam U - The type of the transformed value
39
- * @param mapper - Function to transform the Right value
40
- * @returns New Either with the transformed Right value, or the same Left if error
41
- *
42
- * @example
43
- * ```typescript
44
- * right(5).map(x => x * 2) // Right(10)
45
- * left("error").map(x => x * 2) // Left("error")
46
- * ```
47
- */
48
- map: <U>(mapper: (right: T) => U) => Either<E, U>;
49
- /**
50
- * Returns this Either if it's Right, otherwise returns the result of the fallback function.
51
- *
52
- * @typeParam EE - The type of the error in the fallback Either
53
- * @param fallback - Function that takes the Left value and returns an alternative Either
54
- * @returns This Either if Right, otherwise the Either returned by the fallback function
55
- *
56
- * @example
57
- * ```typescript
58
- * right(42).orElse((err) => right(0)) // Right(42)
59
- * left("error").orElse((err) => right(0)) // Right(0)
60
- * ```
61
- */
62
- orElse: <EE>(fallback: (left: E) => Either<EE, T>) => Either<E | EE, T>;
63
- /**
64
- * Applies a function wrapped in an Either to a value wrapped in an Either.
65
- *
66
- * @typeParam A - The type of the argument value
67
- * @typeParam U - The type of the function's return value
68
- * @param arg - Either containing the argument to apply the function to
69
- * @returns Either containing the function result, or the first Left if any Either is Left
70
- *
71
- * @example
72
- * ```typescript
73
- * const add = (x: number) => (y: number) => x + y;
74
- * right(add(5)).ap(right(3)) // Right(8)
75
- * right(add(5)).ap(left("err")) // Left("err")
76
- * left("err").ap(right(3)) // Left("err")
77
- * ```
78
- */
79
- ap: <EE, A, U>(this: Either<E, (a: A) => U>, arg: Either<EE, A>) => Either<E | EE, U>;
80
- /**
81
- * Swaps the Left and Right sides of the Either.
82
- *
83
- * @returns Either with Left and Right sides swapped
84
- *
85
- * @example
86
- * ```typescript
87
- * right(42).swap() // Left(42)
88
- * left("error").swap() // Right("error")
89
- * ```
90
- */
91
- swap: () => Either<T, E>;
92
- /**
93
- * Combines this Either with another Either into a tuple.
94
- *
95
- * @typeParam EE - Left type of the Either to combine with
96
- * @typeParam A - Right type of the Either to combine with
97
- * @param eitherA - The Either to combine with this one
98
- * @returns Either containing a tuple of both Right values, or the first Left if any Either is Left
99
- *
100
- * @example
101
- * ```typescript
102
- * right("Alice").zip(right(30)) // Right(["Alice", 30])
103
- * right("Alice").zip(left("No age")) // Left("No age")
104
- * left("No name").zip(right(30)) // Left("No name")
105
- * ```
106
- */
107
- zip: <EE, A>(eitherA: Either<EE, A>) => Either<E | EE, readonly [T, A]>;
108
- /**
109
- * Flattens a nested Either structure by removing one level of nesting.
110
- *
111
- * @typeParam EE - Left type of the inner Either
112
- * @typeParam U - Right type of the inner Either
113
- * @returns The inner Either if this Either is Right, otherwise this Either unchanged
114
- *
115
- * @example
116
- * ```typescript
117
- * right(right(42)).flatten() // Right(42)
118
- * right(left("inner error")).flatten() // Left("inner error")
119
- *
120
- * ```
121
- */
122
- flatten: <EE, U>(this: Either<E, Either<EE, U>>) => Either<E | EE, U>;
123
- /**
124
- * Chains Either-returning operations together (monadic bind).
125
- *
126
- * @typeParam EE - The error type of the Either returned by the mapper
127
- * @typeParam U - The success type of the Either returned by the mapper
128
- * @param mapper - Function that takes a Right value and returns an Either
129
- * @returns The Either returned by mapper if this Either is Right, otherwise this Either unchanged
130
- *
131
- * @example
132
- * ```typescript
133
- * const safeDivide = (x: number, y: number) =>
134
- * y === 0 ? left("Division by zero") : right(x / y);
135
- *
136
- * right(10).flatMap(x => safeDivide(x, 2)) // Right(5)
137
- * right(10).flatMap(x => safeDivide(x, 0)) // Left("Division by zero")
138
- * left("error").flatMap(x => safeDivide(x, 2)) // Left("error") - mapper not called
139
- * ```
140
- */
141
- flatMap: <EE, U>(mapper: (right: T) => Either<EE, U>) => Either<E | EE, U>;
142
- /**
143
- * Performs a side effect if this Either is Right, returning the original Either unchanged.
144
- * If this Either is Left, the side effect is not executed and the Either is returned as-is.
145
- *
146
- * @param sideEffect - Function to execute with the Right value (return value is ignored)
147
- * @returns The same Either instance unchanged
148
- *
149
- * @example
150
- * ```typescript
151
- * right(42)
152
- * .tap(value => console.log(`Got value: ${value}`)) // Logs: "Got value: 42"
153
- * left("error")
154
- * .tap(value => console.log(`Got value: ${value}`)) // No log output
155
- *
156
- * ```
157
- */
158
- tap: (sideEffect: (right: T) => void) => Either<E, T>;
159
- /**
160
- * Pattern matches on the Either, executing different functions based on its state.
161
- *
162
- * @typeParam U - The return type of both matcher functions
163
- * @param onLeft - Function to execute if Either is Left, receives the Left value
164
- * @param onRight - Function to execute if Either is Right, receives the Right value
165
- * @returns The result of the executed function
166
- *
167
- * @example
168
- * ```typescript
169
- * right(42).match(
170
- * (err) => `Error: ${err}`,
171
- * (val) => `Value: ${val}`
172
- * ) // "Value: 42"
173
- *
174
- * left("Not a number").match(
175
- * (err) => `Error: ${err}`,
176
- * (val) => `Value: ${val}`
177
- * ) // "Error: Not a number"
178
- * ```
179
- */
180
- match: <U>(onLeft: (left: E) => U, onRight: (right: T) => U) => U;
181
- /**
182
- * Extracts the Right value from the Either, or returns a fallback value if Left.
183
- *
184
- * @param fallback - Function that takes the Left value and returns a default value of type T
185
- * @returns The Right value if present, otherwise the result of the fallback function
186
- *
187
- * @example
188
- * ```typescript
189
- * right(42).getOrElse((err) => 0) // 42
190
- * left("error").getOrElse((err) => 0) // 0
191
- * ```
192
- */
193
- getOrElse: (fallback: (left: E) => T) => T;
194
- /**
195
- * Converts the Either to a Result type, which is an object with `ok` and `error` or `value` properties.
196
- *
197
- * @returns A Result object representing the Either's state
198
- *
199
- * @example
200
- * ```typescript
201
- * const result = right(42).toResult();
202
- * console.log(result.ok); // true
203
- * console.log(result.value); // 42
204
- *
205
- * const errorResult = left("error").toResult();
206
- * console.log(errorResult.ok); // false
207
- * console.log(errorResult.error); // "error"
208
- * ```
209
- */
210
- toResult: () => EitherResult<E, T>;
211
- };
212
- //#endregion
213
- export { Right as a, Left as i, EitherResult as n, EitherValue as r, Either as t };
package/dist/either.d.mts DELETED
@@ -1,3 +0,0 @@
1
- import { a as fromOption, c as tryCatch, i as fromNullable, n as map3, o as left, r as sequence, s as right, t as map2 } from "./helpers-Bw8McftR.mjs";
2
- import { a as Right, i as Left, n as EitherResult, r as EitherValue, t as Either } from "./either-CWllQk7N.mjs";
3
- export { type Either, EitherResult, EitherValue, Left, Right, fromNullable, fromOption, left, map2, map3, right, sequence, tryCatch };
package/dist/either.mjs DELETED
@@ -1,65 +0,0 @@
1
- import { a as tryCatch, i as right, n as fromOption, r as left, t as fromNullable } from "./constructors-pI0lvrQE.mjs";
2
-
3
- //#region src/either/helpers.ts
4
- /**
5
- * Combines two Eithers using a mapping function.
6
- * Returns the mapped result if both Eithers are Right, otherwise the first Left.
7
- *
8
- * @param eitherA - First Either to combine
9
- * @param eitherB - Second Either to combine
10
- * @param mapper - Function to combine both Right values
11
- * @returns Either containing the mapped result, or the first Left
12
- *
13
- * @example
14
- * ```typescript
15
- * map2(right("John"), right("Doe"), (first, last) => `${first} ${last}`)
16
- * // Right("John Doe")
17
- * ```
18
- */
19
- function map2(eitherA, eitherB, mapper) {
20
- return eitherA.map((a) => (b) => mapper(a, b)).ap(eitherB);
21
- }
22
- /**
23
- * Combines three Eithers using a mapping function.
24
- * Returns the mapped result if all Eithers are Right, otherwise the first Left.
25
- *
26
- * @param eitherA - First Either to combine
27
- * @param eitherB - Second Either to combine
28
- * @param eitherC - Third Either to combine
29
- * @param mapper - Function to combine all three Right values
30
- * @returns Either containing the mapped result, or the first Left
31
- *
32
- * @example
33
- * ```typescript
34
- * map3(right(1), right(2), right(3), (a, b, c) => a + b + c)
35
- * // Right(6)
36
- * ```
37
- */
38
- function map3(eitherA, eitherB, eitherC, mapper) {
39
- return eitherA.map((a) => (b) => (c) => mapper(a, b, c)).ap(eitherB).ap(eitherC);
40
- }
41
- /**
42
- * Converts an array of Eithers into an Either of array.
43
- * Returns Right with all values if all Eithers are Right, otherwise the first Left.
44
- *
45
- * @param eithers - Array of Eithers to sequence
46
- * @returns Either containing array of all values, or the first Left
47
- *
48
- * @example
49
- * ```typescript
50
- * sequence([right(1), right(2), right(3)]) // Right([1, 2, 3])
51
- * sequence([right(1), left("error")]) // Left("error")
52
- * ```
53
- */
54
- function sequence(eithers) {
55
- const out = [];
56
- for (const either of eithers) {
57
- const result = either.toResult();
58
- if (!result.ok) return left(result.error);
59
- out.push(result.value);
60
- }
61
- return right(out);
62
- }
63
-
64
- //#endregion
65
- export { fromNullable, fromOption, left, map2, map3, right, sequence, tryCatch };