@nlozgachev/pipelined 0.6.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 (60) hide show
  1. package/esm/src/Core/Logged.js +111 -0
  2. package/esm/src/Core/Option.js +4 -1
  3. package/esm/src/Core/Predicate.js +133 -0
  4. package/esm/src/Core/Refinement.js +115 -0
  5. package/esm/src/Core/RemoteData.js +3 -0
  6. package/esm/src/Core/Result.js +4 -0
  7. package/esm/src/Core/State.js +181 -0
  8. package/esm/src/Core/Task.js +36 -0
  9. package/esm/src/Core/TaskOption.js +1 -0
  10. package/esm/src/Core/TaskResult.js +2 -0
  11. package/esm/src/Core/TaskValidation.js +5 -1
  12. package/esm/src/Core/These.js +4 -0
  13. package/esm/src/Core/Validation.js +4 -0
  14. package/esm/src/Core/index.js +4 -0
  15. package/package.json +1 -1
  16. package/script/src/Core/Logged.js +114 -0
  17. package/script/src/Core/Option.js +4 -1
  18. package/script/src/Core/Predicate.js +136 -0
  19. package/script/src/Core/Refinement.js +118 -0
  20. package/script/src/Core/RemoteData.js +3 -0
  21. package/script/src/Core/Result.js +4 -0
  22. package/script/src/Core/State.js +184 -0
  23. package/script/src/Core/Task.js +36 -0
  24. package/script/src/Core/TaskOption.js +1 -0
  25. package/script/src/Core/TaskResult.js +2 -0
  26. package/script/src/Core/TaskValidation.js +5 -1
  27. package/script/src/Core/These.js +4 -0
  28. package/script/src/Core/Validation.js +4 -0
  29. package/script/src/Core/index.js +4 -0
  30. package/types/src/Composition/on.d.ts.map +1 -1
  31. package/types/src/Core/InternalTypes.d.ts +3 -0
  32. package/types/src/Core/InternalTypes.d.ts.map +1 -1
  33. package/types/src/Core/Logged.d.ts +126 -0
  34. package/types/src/Core/Logged.d.ts.map +1 -0
  35. package/types/src/Core/Option.d.ts +6 -3
  36. package/types/src/Core/Option.d.ts.map +1 -1
  37. package/types/src/Core/Predicate.d.ts +161 -0
  38. package/types/src/Core/Predicate.d.ts.map +1 -0
  39. package/types/src/Core/Refinement.d.ts +138 -0
  40. package/types/src/Core/Refinement.d.ts.map +1 -0
  41. package/types/src/Core/RemoteData.d.ts +5 -2
  42. package/types/src/Core/RemoteData.d.ts.map +1 -1
  43. package/types/src/Core/Result.d.ts +7 -3
  44. package/types/src/Core/Result.d.ts.map +1 -1
  45. package/types/src/Core/State.d.ts +192 -0
  46. package/types/src/Core/State.d.ts.map +1 -0
  47. package/types/src/Core/Task.d.ts +30 -0
  48. package/types/src/Core/Task.d.ts.map +1 -1
  49. package/types/src/Core/TaskOption.d.ts +2 -1
  50. package/types/src/Core/TaskOption.d.ts.map +1 -1
  51. package/types/src/Core/TaskResult.d.ts +4 -2
  52. package/types/src/Core/TaskResult.d.ts.map +1 -1
  53. package/types/src/Core/TaskValidation.d.ts +4 -2
  54. package/types/src/Core/TaskValidation.d.ts.map +1 -1
  55. package/types/src/Core/These.d.ts +6 -2
  56. package/types/src/Core/These.d.ts.map +1 -1
  57. package/types/src/Core/Validation.d.ts +7 -3
  58. package/types/src/Core/Validation.d.ts.map +1 -1
  59. package/types/src/Core/index.d.ts +4 -0
  60. package/types/src/Core/index.d.ts.map +1 -1
@@ -0,0 +1,111 @@
1
+ export var Logged;
2
+ (function (Logged) {
3
+ /**
4
+ * Wraps a pure value into a `Logged` with an empty log.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * Logged.make<string, number>(42); // { value: 42, log: [] }
9
+ * ```
10
+ */
11
+ Logged.make = (value) => ({ value, log: [] });
12
+ /**
13
+ * Creates a `Logged` that records a single log entry and produces no
14
+ * meaningful value. Use this to append to the log inside a `chain`.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * Logged.tell("operation completed"); // { value: undefined, log: ["operation completed"] }
19
+ * ```
20
+ */
21
+ Logged.tell = (entry) => ({ value: undefined, log: [entry] });
22
+ /**
23
+ * Transforms the value inside a `Logged` without affecting the log.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * pipe(
28
+ * Logged.of<string, number>(5),
29
+ * Logged.map(n => n * 2),
30
+ * ); // { value: 10, log: [] }
31
+ * ```
32
+ */
33
+ Logged.map = (f) => (data) => ({
34
+ value: f(data.value),
35
+ log: data.log,
36
+ });
37
+ /**
38
+ * Sequences two `Logged` computations, concatenating their logs.
39
+ * The value from the first is passed to `f`; the resulting log entries are
40
+ * appended after the entries from the first.
41
+ *
42
+ * Data-last — the first computation is the data being piped.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const result = pipe(
47
+ * Logged.of<string, number>(1),
48
+ * Logged.chain(n => pipe(Logged.tell("step"), Logged.map(() => n + 1))),
49
+ * Logged.chain(n => pipe(Logged.tell("done"), Logged.map(() => n * 10))),
50
+ * );
51
+ *
52
+ * Logged.run(result); // [20, ["step", "done"]]
53
+ * ```
54
+ */
55
+ Logged.chain = (f) => (data) => {
56
+ const next = f(data.value);
57
+ return { value: next.value, log: [...data.log, ...next.log] };
58
+ };
59
+ /**
60
+ * Applies a function wrapped in a `Logged` to a value wrapped in a `Logged`,
61
+ * concatenating both logs.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * const fn: Logged<string, (n: number) => number> = {
66
+ * value: n => n * 2,
67
+ * log: ["fn-loaded"],
68
+ * };
69
+ * const arg: Logged<string, number> = { value: 5, log: ["arg-loaded"] };
70
+ *
71
+ * const result = pipe(fn, Logged.ap(arg));
72
+ * Logged.run(result); // [10, ["fn-loaded", "arg-loaded"]]
73
+ * ```
74
+ */
75
+ Logged.ap = (arg) => (data) => ({
76
+ value: data.value(arg.value),
77
+ log: [...data.log, ...arg.log],
78
+ });
79
+ /**
80
+ * Runs a side effect on the value without changing the `Logged`.
81
+ * Useful for debugging or inspecting intermediate values.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * pipe(
86
+ * Logged.of<string, number>(42),
87
+ * Logged.tap(n => console.log("value:", n)),
88
+ * );
89
+ * ```
90
+ */
91
+ Logged.tap = (f) => (data) => {
92
+ f(data.value);
93
+ return data;
94
+ };
95
+ /**
96
+ * Extracts the value and log as a `readonly [A, ReadonlyArray<W>]` tuple.
97
+ * Use this at the boundary where you need to consume both.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const result = pipe(
102
+ * Logged.of<string, number>(1),
103
+ * Logged.chain(n => pipe(Logged.tell("incremented"), Logged.map(() => n + 1))),
104
+ * );
105
+ *
106
+ * const [value, log] = Logged.run(result);
107
+ * // value = 2, log = ["incremented"]
108
+ * ```
109
+ */
110
+ Logged.run = (data) => [data.value, data.log];
111
+ })(Logged || (Logged = {}));
@@ -127,12 +127,14 @@ export var Option;
127
127
  */
128
128
  Option.match = (cases) => (data) => Option.isSome(data) ? cases.some(data.value) : cases.none();
129
129
  /**
130
- * Returns the value inside a Option, or a default value if None.
130
+ * Returns the value inside an Option, or a default value if None.
131
+ * The default can be a different type, widening the result to `A | B`.
131
132
  *
132
133
  * @example
133
134
  * ```ts
134
135
  * pipe(Option.some(5), Option.getOrElse(0)); // 5
135
136
  * pipe(Option.none(), Option.getOrElse(0)); // 0
137
+ * pipe(Option.none<string>(), Option.getOrElse(null)); // null — typed as string | null
136
138
  * ```
137
139
  */
138
140
  Option.getOrElse = (defaultValue) => (data) => Option.isSome(data) ? data.value : defaultValue;
@@ -167,6 +169,7 @@ export var Option;
167
169
  Option.filter = (predicate) => (data) => Option.isSome(data) && predicate(data.value) ? data : Option.none();
168
170
  /**
169
171
  * Recovers from a None by providing a fallback Option.
172
+ * The fallback can produce a different type, widening the result to `Option<A | B>`.
170
173
  */
171
174
  Option.recover = (fallback) => (data) => Option.isSome(data) ? data : fallback();
172
175
  /**
@@ -0,0 +1,133 @@
1
+ export var Predicate;
2
+ (function (Predicate) {
3
+ /**
4
+ * Negates a predicate: the result passes exactly when the original fails.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * const isBlank: Predicate<string> = s => s.trim().length === 0;
9
+ * const isNotBlank = Predicate.not(isBlank);
10
+ *
11
+ * isNotBlank("hello"); // true
12
+ * isNotBlank(" "); // false
13
+ * ```
14
+ */
15
+ Predicate.not = (p) => (a) => !p(a);
16
+ /**
17
+ * Combines two predicates with logical AND: passes only when both hold.
18
+ *
19
+ * Data-last — the first predicate is the data being piped.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * const isPositive: Predicate<number> = n => n > 0;
24
+ * const isEven: Predicate<number> = n => n % 2 === 0;
25
+ *
26
+ * const isPositiveEven: Predicate<number> = pipe(isPositive, Predicate.and(isEven));
27
+ *
28
+ * isPositiveEven(4); // true
29
+ * isPositiveEven(3); // false — positive but odd
30
+ * isPositiveEven(-2); // false — even but not positive
31
+ * ```
32
+ */
33
+ Predicate.and = (second) => (first) => (a) => first(a) && second(a);
34
+ /**
35
+ * Combines two predicates with logical OR: passes when either holds.
36
+ *
37
+ * Data-last — the first predicate is the data being piped.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const isChild: Predicate<number> = n => n < 13;
42
+ * const isSenior: Predicate<number> = n => n >= 65;
43
+ *
44
+ * const getsDiscount: Predicate<number> = pipe(isChild, Predicate.or(isSenior));
45
+ *
46
+ * getsDiscount(8); // true
47
+ * getsDiscount(70); // true
48
+ * getsDiscount(30); // false
49
+ * ```
50
+ */
51
+ Predicate.or = (second) => (first) => (a) => first(a) || second(a);
52
+ /**
53
+ * Adapts a `Predicate<A>` to work on a different input type `B` by applying `f`
54
+ * to extract the relevant `A` from a `B` before running the check.
55
+ *
56
+ * Data-last — the predicate is the data being piped; `f` is the extractor.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * type User = { name: string; age: number };
61
+ *
62
+ * const isAdult: Predicate<number> = n => n >= 18;
63
+ *
64
+ * // Lift isAdult to work on Users by extracting the age field
65
+ * const isAdultUser: Predicate<User> = pipe(
66
+ * isAdult,
67
+ * Predicate.using((u: User) => u.age)
68
+ * );
69
+ *
70
+ * isAdultUser({ name: "Alice", age: 30 }); // true
71
+ * isAdultUser({ name: "Bob", age: 15 }); // false
72
+ * ```
73
+ */
74
+ Predicate.using = (f) => (p) => (b) => p(f(b));
75
+ /**
76
+ * Combines an array of predicates with AND: passes only when every predicate holds.
77
+ * Returns `true` for an empty array (vacuous truth).
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * const checks: Predicate<string>[] = [
82
+ * s => s.length > 0,
83
+ * s => s.length <= 100,
84
+ * s => !s.includes("<"),
85
+ * ];
86
+ *
87
+ * Predicate.all(checks)("hello"); // true
88
+ * Predicate.all(checks)(""); // false — too short
89
+ * Predicate.all(checks)("<b>"); // false — contains "<"
90
+ * Predicate.all([])("anything"); // true
91
+ * ```
92
+ */
93
+ Predicate.all = (predicates) => (a) => predicates.every((p) => p(a));
94
+ /**
95
+ * Combines an array of predicates with OR: passes when at least one holds.
96
+ * Returns `false` for an empty array.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * const acceptedFormats: Predicate<string>[] = [
101
+ * s => s.endsWith(".jpg"),
102
+ * s => s.endsWith(".png"),
103
+ * s => s.endsWith(".webp"),
104
+ * ];
105
+ *
106
+ * Predicate.any(acceptedFormats)("photo.jpg"); // true
107
+ * Predicate.any(acceptedFormats)("photo.gif"); // false
108
+ * Predicate.any([])("anything"); // false
109
+ * ```
110
+ */
111
+ Predicate.any = (predicates) => (a) => predicates.some((p) => p(a));
112
+ /**
113
+ * Converts a `Refinement<A, B>` into a `Predicate<A>`, discarding the compile-time
114
+ * narrowing. Use this when you want to combine a type guard with plain predicates
115
+ * using `and`, `or`, or `all`.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * const isString: Refinement<unknown, string> =
120
+ * Refinement.make(x => typeof x === "string");
121
+ *
122
+ * const isShortString: Predicate<unknown> = pipe(
123
+ * Predicate.fromRefinement(isString),
124
+ * Predicate.and(x => (x as string).length < 10)
125
+ * );
126
+ *
127
+ * isShortString("hi"); // true
128
+ * isShortString("a very long string that exceeds ten characters"); // false
129
+ * isShortString(42); // false
130
+ * ```
131
+ */
132
+ Predicate.fromRefinement = (r) => r;
133
+ })(Predicate || (Predicate = {}));
@@ -0,0 +1,115 @@
1
+ import { Option } from "./Option.js";
2
+ import { Result } from "./Result.js";
3
+ export var Refinement;
4
+ (function (Refinement) {
5
+ /**
6
+ * Creates a `Refinement<A, B>` from a plain boolean predicate.
7
+ *
8
+ * This is an unsafe cast — the caller is responsible for ensuring that the
9
+ * predicate truly characterises values of type `B`. Use this only when
10
+ * bootstrapping a new refinement; prefer `compose`, `and`, or `or` to build
11
+ * derived refinements from existing ones.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * type PositiveNumber = number & { readonly _tag: "PositiveNumber" };
16
+ *
17
+ * const isPositive: Refinement<number, PositiveNumber> =
18
+ * Refinement.make(n => n > 0);
19
+ * ```
20
+ */
21
+ Refinement.make = (f) => f;
22
+ /**
23
+ * Chains two refinements: if `ab` narrows `A` to `B` and `bc` narrows `B` to `C`,
24
+ * the result narrows `A` directly to `C`.
25
+ *
26
+ * Data-last — the first refinement `ab` is the data being piped.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * type NonEmptyString = string & { readonly _tag: "NonEmpty" };
31
+ * type TrimmedString = NonEmptyString & { readonly _tag: "Trimmed" };
32
+ *
33
+ * const isNonEmpty: Refinement<string, NonEmptyString> =
34
+ * Refinement.make(s => s.length > 0);
35
+ * const isTrimmed: Refinement<NonEmptyString, TrimmedString> =
36
+ * Refinement.make(s => s === s.trim());
37
+ *
38
+ * const isNonEmptyTrimmed: Refinement<string, TrimmedString> = pipe(
39
+ * isNonEmpty,
40
+ * Refinement.compose(isTrimmed)
41
+ * );
42
+ * ```
43
+ */
44
+ Refinement.compose = (bc) => (ab) => (a) => ab(a) && bc(a);
45
+ /**
46
+ * Intersects two refinements: the result narrows `A` to `B & C`, passing only
47
+ * when both refinements hold simultaneously.
48
+ *
49
+ * Data-last — the first refinement is the data being piped.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const isString: Refinement<unknown, string> = Refinement.make(x => typeof x === "string");
54
+ * const isNonEmpty: Refinement<unknown, { length: number }> =
55
+ * Refinement.make(x => (x as any).length > 0);
56
+ *
57
+ * const isNonEmptyString = pipe(isString, Refinement.and(isNonEmpty));
58
+ * isNonEmptyString("hi"); // true
59
+ * isNonEmptyString(""); // false
60
+ * ```
61
+ */
62
+ Refinement.and = (second) => (first) => (a) => first(a) && second(a);
63
+ /**
64
+ * Unions two refinements: the result narrows `A` to `B | C`, passing when either
65
+ * refinement holds.
66
+ *
67
+ * Data-last — the first refinement is the data being piped.
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * const isString: Refinement<unknown, string> = Refinement.make(x => typeof x === "string");
72
+ * const isNumber: Refinement<unknown, number> = Refinement.make(x => typeof x === "number");
73
+ *
74
+ * const isStringOrNumber = pipe(isString, Refinement.or(isNumber));
75
+ * isStringOrNumber("hi"); // true
76
+ * isStringOrNumber(42); // true
77
+ * isStringOrNumber(true); // false
78
+ * ```
79
+ */
80
+ Refinement.or = (second) => (first) => (a) => first(a) || second(a);
81
+ /**
82
+ * Converts a `Refinement<A, B>` into a function `(a: A) => Option<B>`.
83
+ *
84
+ * Returns `Some(a)` when the refinement holds, `None` otherwise. Useful for
85
+ * integrating runtime validation into an `Option`-based pipeline.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * type PositiveNumber = number & { readonly _tag: "Positive" };
90
+ * const isPositive: Refinement<number, PositiveNumber> =
91
+ * Refinement.make(n => n > 0);
92
+ *
93
+ * pipe(-1, Refinement.toFilter(isPositive)); // None
94
+ * pipe(42, Refinement.toFilter(isPositive)); // Some(42)
95
+ * ```
96
+ */
97
+ Refinement.toFilter = (r) => (a) => r(a) ? Option.some(a) : Option.none();
98
+ /**
99
+ * Converts a `Refinement<A, B>` into a function `(a: A) => Result<E, B>`.
100
+ *
101
+ * Returns `Ok(a)` when the refinement holds, `Err(onFail(a))` otherwise. Use
102
+ * this to surface validation failures as typed errors inside a `Result` pipeline.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * type NonEmptyString = string & { readonly _tag: "NonEmpty" };
107
+ * const isNonEmpty: Refinement<string, NonEmptyString> =
108
+ * Refinement.make(s => s.length > 0);
109
+ *
110
+ * pipe("", Refinement.toResult(isNonEmpty, () => "must not be empty")); // Err(...)
111
+ * pipe("hi", Refinement.toResult(isNonEmpty, () => "must not be empty")); // Ok("hi")
112
+ * ```
113
+ */
114
+ Refinement.toResult = (r, onFail) => (a) => r(a) ? Result.ok(a) : Result.err(onFail(a));
115
+ })(Refinement || (Refinement = {}));
@@ -153,11 +153,13 @@ export var RemoteData;
153
153
  };
154
154
  /**
155
155
  * Returns the success value or a default value if the RemoteData is not Success.
156
+ * The default can be a different type, widening the result to `A | B`.
156
157
  *
157
158
  * @example
158
159
  * ```ts
159
160
  * pipe(RemoteData.success(5), RemoteData.getOrElse(0)); // 5
160
161
  * pipe(RemoteData.loading(), RemoteData.getOrElse(0)); // 0
162
+ * pipe(RemoteData.loading<string, number>(), RemoteData.getOrElse(null)); // null — typed as number | null
161
163
  * ```
162
164
  */
163
165
  RemoteData.getOrElse = (defaultValue) => (data) => RemoteData.isSuccess(data) ? data.value : defaultValue;
@@ -180,6 +182,7 @@ export var RemoteData;
180
182
  };
181
183
  /**
182
184
  * Recovers from a Failure state by providing a fallback RemoteData.
185
+ * The fallback can produce a different success type, widening the result to `RemoteData<E, A | B>`.
183
186
  */
184
187
  RemoteData.recover = (fallback) => (data) => RemoteData.isFailure(data) ? fallback(data.error) : data;
185
188
  /**
@@ -102,11 +102,13 @@ export var Result;
102
102
  Result.match = (cases) => (data) => Result.isOk(data) ? cases.ok(data.value) : cases.err(data.error);
103
103
  /**
104
104
  * Returns the success value or a default value if the Result is an error.
105
+ * The default can be a different type, widening the result to `A | B`.
105
106
  *
106
107
  * @example
107
108
  * ```ts
108
109
  * pipe(Result.ok(5), Result.getOrElse(0)); // 5
109
110
  * pipe(Result.err("error"), Result.getOrElse(0)); // 0
111
+ * pipe(Result.err("error"), Result.getOrElse(null)); // null — typed as number | null
110
112
  * ```
111
113
  */
112
114
  Result.getOrElse = (defaultValue) => (data) => Result.isOk(data) ? data.value : defaultValue;
@@ -130,10 +132,12 @@ export var Result;
130
132
  };
131
133
  /**
132
134
  * Recovers from an error by providing a fallback Result.
135
+ * The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
133
136
  */
134
137
  Result.recover = (fallback) => (data) => Result.isOk(data) ? data : fallback();
135
138
  /**
136
139
  * Recovers from an error unless it matches the blocked error.
140
+ * The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
137
141
  */
138
142
  Result.recoverUnless = (blockedErr, fallback) => (data) => Result.isErr(data) && data.error !== blockedErr ? fallback() : data;
139
143
  /**
@@ -0,0 +1,181 @@
1
+ export var State;
2
+ (function (State) {
3
+ /**
4
+ * Lifts a pure value into a State computation. The state passes through unchanged.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * State.run(10)(State.resolve(42)); // [42, 10] — value 42, state unchanged
9
+ * ```
10
+ */
11
+ State.resolve = (value) => (s) => [value, s];
12
+ /**
13
+ * Produces the current state as the value, without modifying it.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const readStack: State<string[], string[]> = State.get();
18
+ * State.run(["a", "b"])(readStack); // [["a", "b"], ["a", "b"]]
19
+ * ```
20
+ */
21
+ State.get = () => (s) => [s, s];
22
+ /**
23
+ * Reads a projection of the state without modifying it.
24
+ * Equivalent to `pipe(State.get(), State.map(f))` but more direct.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * type AppState = { count: number; label: string };
29
+ * const readCount: State<AppState, number> = State.gets(s => s.count);
30
+ * State.run({ count: 5, label: "x" })(readCount); // [5, { count: 5, label: "x" }]
31
+ * ```
32
+ */
33
+ State.gets = (f) => (s) => [f(s), s];
34
+ /**
35
+ * Replaces the current state with a new value. Produces no meaningful value.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const reset: State<number, undefined> = State.put(0);
40
+ * State.run(99)(reset); // [undefined, 0]
41
+ * ```
42
+ */
43
+ State.put = (newState) => (_s) => [undefined, newState];
44
+ /**
45
+ * Applies a function to the current state to produce the next state.
46
+ * Produces no meaningful value.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const push = (item: string): State<string[], undefined> =>
51
+ * State.modify(stack => [...stack, item]);
52
+ *
53
+ * State.run(["a"])(push("b")); // [undefined, ["a", "b"]]
54
+ * ```
55
+ */
56
+ State.modify = (f) => (s) => [undefined, f(s)];
57
+ /**
58
+ * Transforms the value produced by a State computation.
59
+ * The state transformation is unchanged.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const readLength: State<string[], number> = pipe(
64
+ * State.get<string[]>(),
65
+ * State.map(stack => stack.length),
66
+ * );
67
+ *
68
+ * State.run(["a", "b", "c"])(readLength); // [3, ["a", "b", "c"]]
69
+ * ```
70
+ */
71
+ State.map = (f) => (st) => (s) => {
72
+ const [a, s1] = st(s);
73
+ return [f(a), s1];
74
+ };
75
+ /**
76
+ * Sequences two State computations. The state output of the first is passed
77
+ * as the state input to the second.
78
+ *
79
+ * Data-last — the first computation is the data being piped.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * const push = (item: string): State<string[], undefined> =>
84
+ * State.modify(stack => [...stack, item]);
85
+ *
86
+ * const program = pipe(
87
+ * push("a"),
88
+ * State.chain(() => push("b")),
89
+ * State.chain(() => State.get<string[]>()),
90
+ * );
91
+ *
92
+ * State.evaluate([])(program); // ["a", "b"]
93
+ * ```
94
+ */
95
+ State.chain = (f) => (st) => (s) => {
96
+ const [a, s1] = st(s);
97
+ return f(a)(s1);
98
+ };
99
+ /**
100
+ * Applies a function wrapped in a State to a value wrapped in a State.
101
+ * The function computation runs first; its output state is the input to the
102
+ * argument computation.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * const addCounted = (n: number) => (m: number) => n + m;
107
+ * const program = pipe(
108
+ * State.resolve<number, typeof addCounted>(addCounted),
109
+ * State.ap(State.gets((s: number) => s * 2)),
110
+ * State.ap(State.gets((s: number) => s)),
111
+ * );
112
+ *
113
+ * State.evaluate(3)(program); // 6 + 3 = 9
114
+ * ```
115
+ */
116
+ State.ap = (arg) => (fn) => (s) => {
117
+ const [f, s1] = fn(s);
118
+ const [a, s2] = arg(s1);
119
+ return [f(a), s2];
120
+ };
121
+ /**
122
+ * Runs a side effect on the produced value without changing the State computation.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * pipe(
127
+ * State.get<number>(),
128
+ * State.tap(n => console.log("current:", n)),
129
+ * State.chain(() => State.modify(n => n + 1)),
130
+ * );
131
+ * ```
132
+ */
133
+ State.tap = (f) => (st) => (s) => {
134
+ const [a, s1] = st(s);
135
+ f(a);
136
+ return [a, s1];
137
+ };
138
+ /**
139
+ * Runs a State computation with an initial state, returning both the
140
+ * produced value and the final state as a pair.
141
+ *
142
+ * Data-last — the computation is the data being piped.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * const program = pipe(
147
+ * State.modify<number>(n => n + 1),
148
+ * State.chain(() => State.get<number>()),
149
+ * );
150
+ *
151
+ * State.run(0)(program); // [1, 1]
152
+ * ```
153
+ */
154
+ State.run = (initialState) => (st) => st(initialState);
155
+ /**
156
+ * Runs a State computation with an initial state, returning only the
157
+ * produced value (discarding the final state).
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * State.evaluate([])(pipe(
162
+ * State.modify<string[]>(s => [...s, "x"]),
163
+ * State.chain(() => State.get<string[]>()),
164
+ * )); // ["x"]
165
+ * ```
166
+ */
167
+ State.evaluate = (initialState) => (st) => st(initialState)[0];
168
+ /**
169
+ * Runs a State computation with an initial state, returning only the
170
+ * final state (discarding the produced value).
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * State.execute(0)(pipe(
175
+ * State.modify<number>(n => n + 10),
176
+ * State.chain(() => State.modify<number>(n => n * 2)),
177
+ * )); // 20
178
+ * ```
179
+ */
180
+ State.execute = (initialState) => (st) => st(initialState)[1];
181
+ })(State || (State = {}));
@@ -159,6 +159,42 @@ export var Task;
159
159
  });
160
160
  return run();
161
161
  });
162
+ /**
163
+ * Resolves with the value of the first Task to complete. All Tasks start
164
+ * immediately; the rest are abandoned once one resolves.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * const fast = Task.from(() => new Promise<string>(r => setTimeout(() => r("fast"), 10)));
169
+ * const slow = Task.from(() => new Promise<string>(r => setTimeout(() => r("slow"), 200)));
170
+ *
171
+ * await Task.race([fast, slow])(); // "fast"
172
+ * ```
173
+ */
174
+ Task.race = (tasks) => Task.from(() => Promise.race(tasks.map(toPromise)));
175
+ /**
176
+ * Runs an array of Tasks one at a time in order, collecting all results.
177
+ * Each Task starts only after the previous one resolves.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * let log: number[] = [];
182
+ * const makeTask = (n: number) => Task.from(() => {
183
+ * log.push(n);
184
+ * return Promise.resolve(n);
185
+ * });
186
+ *
187
+ * await Task.sequential([makeTask(1), makeTask(2), makeTask(3)])();
188
+ * // log = [1, 2, 3] — tasks ran in order
189
+ * ```
190
+ */
191
+ Task.sequential = (tasks) => Task.from(async () => {
192
+ const results = [];
193
+ for (const task of tasks) {
194
+ results.push(await toPromise(task));
195
+ }
196
+ return results;
197
+ });
162
198
  /**
163
199
  * Converts a `Task<A>` into a `Task<Result<E, A>>`, resolving to `Err` if the
164
200
  * Task does not complete within the given time.
@@ -79,6 +79,7 @@ export var TaskOption;
79
79
  TaskOption.match = (cases) => (data) => Task.map(Option.match(cases))(data);
80
80
  /**
81
81
  * Returns the value or a default if the TaskOption resolves to None.
82
+ * The default can be a different type, widening the result to `Task<A | B>`.
82
83
  */
83
84
  TaskOption.getOrElse = (defaultValue) => (data) => Task.map(Option.getOrElse(defaultValue))(data);
84
85
  /**
@@ -50,10 +50,12 @@ export var TaskResult;
50
50
  TaskResult.match = (cases) => (data) => Task.map(Result.match(cases))(data);
51
51
  /**
52
52
  * Recovers from an error by providing a fallback TaskResult.
53
+ * The fallback can produce a different success type, widening the result to `TaskResult<E, A | B>`.
53
54
  */
54
55
  TaskResult.recover = (fallback) => (data) => Task.chain((result) => Result.isErr(result) ? fallback(result.error) : Task.resolve(result))(data);
55
56
  /**
56
57
  * Returns the success value or a default value if the TaskResult is an error.
58
+ * The default can be a different type, widening the result to `Task<A | B>`.
57
59
  */
58
60
  TaskResult.getOrElse = (defaultValue) => (data) => Task.map(Result.getOrElse(defaultValue))(data);
59
61
  /**