@nlozgachev/pipelined 0.6.4

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 (144) hide show
  1. package/README.md +85 -0
  2. package/esm/mod.js +3 -0
  3. package/esm/package.json +3 -0
  4. package/esm/src/Composition/compose.js +3 -0
  5. package/esm/src/Composition/converge.js +3 -0
  6. package/esm/src/Composition/curry.js +42 -0
  7. package/esm/src/Composition/flip.js +20 -0
  8. package/esm/src/Composition/flow.js +8 -0
  9. package/esm/src/Composition/fn.js +85 -0
  10. package/esm/src/Composition/index.js +13 -0
  11. package/esm/src/Composition/juxt.js +3 -0
  12. package/esm/src/Composition/memoize.js +66 -0
  13. package/esm/src/Composition/not.js +25 -0
  14. package/esm/src/Composition/on.js +12 -0
  15. package/esm/src/Composition/pipe.js +3 -0
  16. package/esm/src/Composition/tap.js +33 -0
  17. package/esm/src/Composition/uncurry.js +32 -0
  18. package/esm/src/Core/Arr.js +463 -0
  19. package/esm/src/Core/Deferred.js +26 -0
  20. package/esm/src/Core/InternalTypes.js +1 -0
  21. package/esm/src/Core/Lens.js +98 -0
  22. package/esm/src/Core/Option.js +186 -0
  23. package/esm/src/Core/Optional.js +160 -0
  24. package/esm/src/Core/Reader.js +134 -0
  25. package/esm/src/Core/Rec.js +167 -0
  26. package/esm/src/Core/RemoteData.js +206 -0
  27. package/esm/src/Core/Result.js +164 -0
  28. package/esm/src/Core/Task.js +187 -0
  29. package/esm/src/Core/TaskOption.js +105 -0
  30. package/esm/src/Core/TaskResult.js +125 -0
  31. package/esm/src/Core/TaskValidation.js +101 -0
  32. package/esm/src/Core/These.js +241 -0
  33. package/esm/src/Core/Validation.js +214 -0
  34. package/esm/src/Core/index.js +15 -0
  35. package/esm/src/Types/Brand.js +28 -0
  36. package/esm/src/Types/NonEmptyList.js +14 -0
  37. package/esm/src/Types/index.js +2 -0
  38. package/package.json +61 -0
  39. package/script/mod.js +19 -0
  40. package/script/package.json +3 -0
  41. package/script/src/Composition/compose.js +6 -0
  42. package/script/src/Composition/converge.js +6 -0
  43. package/script/src/Composition/curry.js +48 -0
  44. package/script/src/Composition/flip.js +24 -0
  45. package/script/src/Composition/flow.js +11 -0
  46. package/script/src/Composition/fn.js +98 -0
  47. package/script/src/Composition/index.js +29 -0
  48. package/script/src/Composition/juxt.js +6 -0
  49. package/script/src/Composition/memoize.js +71 -0
  50. package/script/src/Composition/not.js +29 -0
  51. package/script/src/Composition/on.js +16 -0
  52. package/script/src/Composition/pipe.js +6 -0
  53. package/script/src/Composition/tap.js +37 -0
  54. package/script/src/Composition/uncurry.js +38 -0
  55. package/script/src/Core/Arr.js +466 -0
  56. package/script/src/Core/Deferred.js +29 -0
  57. package/script/src/Core/InternalTypes.js +2 -0
  58. package/script/src/Core/Lens.js +101 -0
  59. package/script/src/Core/Option.js +189 -0
  60. package/script/src/Core/Optional.js +163 -0
  61. package/script/src/Core/Reader.js +137 -0
  62. package/script/src/Core/Rec.js +170 -0
  63. package/script/src/Core/RemoteData.js +209 -0
  64. package/script/src/Core/Result.js +167 -0
  65. package/script/src/Core/Task.js +190 -0
  66. package/script/src/Core/TaskOption.js +108 -0
  67. package/script/src/Core/TaskResult.js +128 -0
  68. package/script/src/Core/TaskValidation.js +104 -0
  69. package/script/src/Core/These.js +244 -0
  70. package/script/src/Core/Validation.js +217 -0
  71. package/script/src/Core/index.js +31 -0
  72. package/script/src/Types/Brand.js +31 -0
  73. package/script/src/Types/NonEmptyList.js +18 -0
  74. package/script/src/Types/index.js +18 -0
  75. package/types/mod.d.ts +4 -0
  76. package/types/mod.d.ts.map +1 -0
  77. package/types/src/Composition/compose.d.ts +33 -0
  78. package/types/src/Composition/compose.d.ts.map +1 -0
  79. package/types/src/Composition/converge.d.ts +21 -0
  80. package/types/src/Composition/converge.d.ts.map +1 -0
  81. package/types/src/Composition/curry.d.ts +43 -0
  82. package/types/src/Composition/curry.d.ts.map +1 -0
  83. package/types/src/Composition/flip.d.ts +21 -0
  84. package/types/src/Composition/flip.d.ts.map +1 -0
  85. package/types/src/Composition/flow.d.ts +56 -0
  86. package/types/src/Composition/flow.d.ts.map +1 -0
  87. package/types/src/Composition/fn.d.ts +76 -0
  88. package/types/src/Composition/fn.d.ts.map +1 -0
  89. package/types/src/Composition/index.d.ts +14 -0
  90. package/types/src/Composition/index.d.ts.map +1 -0
  91. package/types/src/Composition/juxt.d.ts +18 -0
  92. package/types/src/Composition/juxt.d.ts.map +1 -0
  93. package/types/src/Composition/memoize.d.ts +46 -0
  94. package/types/src/Composition/memoize.d.ts.map +1 -0
  95. package/types/src/Composition/not.d.ts +26 -0
  96. package/types/src/Composition/not.d.ts.map +1 -0
  97. package/types/src/Composition/on.d.ts +13 -0
  98. package/types/src/Composition/on.d.ts.map +1 -0
  99. package/types/src/Composition/pipe.d.ts +56 -0
  100. package/types/src/Composition/pipe.d.ts.map +1 -0
  101. package/types/src/Composition/tap.d.ts +31 -0
  102. package/types/src/Composition/tap.d.ts.map +1 -0
  103. package/types/src/Composition/uncurry.d.ts +54 -0
  104. package/types/src/Composition/uncurry.d.ts.map +1 -0
  105. package/types/src/Core/Arr.d.ts +355 -0
  106. package/types/src/Core/Arr.d.ts.map +1 -0
  107. package/types/src/Core/Deferred.d.ts +49 -0
  108. package/types/src/Core/Deferred.d.ts.map +1 -0
  109. package/types/src/Core/InternalTypes.d.ts +20 -0
  110. package/types/src/Core/InternalTypes.d.ts.map +1 -0
  111. package/types/src/Core/Lens.d.ts +118 -0
  112. package/types/src/Core/Lens.d.ts.map +1 -0
  113. package/types/src/Core/Option.d.ts +205 -0
  114. package/types/src/Core/Option.d.ts.map +1 -0
  115. package/types/src/Core/Optional.d.ts +158 -0
  116. package/types/src/Core/Optional.d.ts.map +1 -0
  117. package/types/src/Core/Reader.d.ts +156 -0
  118. package/types/src/Core/Reader.d.ts.map +1 -0
  119. package/types/src/Core/Rec.d.ts +121 -0
  120. package/types/src/Core/Rec.d.ts.map +1 -0
  121. package/types/src/Core/RemoteData.d.ts +192 -0
  122. package/types/src/Core/RemoteData.d.ts.map +1 -0
  123. package/types/src/Core/Result.d.ts +176 -0
  124. package/types/src/Core/Result.d.ts.map +1 -0
  125. package/types/src/Core/Task.d.ts +189 -0
  126. package/types/src/Core/Task.d.ts.map +1 -0
  127. package/types/src/Core/TaskOption.d.ts +120 -0
  128. package/types/src/Core/TaskOption.d.ts.map +1 -0
  129. package/types/src/Core/TaskResult.d.ts +117 -0
  130. package/types/src/Core/TaskResult.d.ts.map +1 -0
  131. package/types/src/Core/TaskValidation.d.ts +119 -0
  132. package/types/src/Core/TaskValidation.d.ts.map +1 -0
  133. package/types/src/Core/These.d.ts +221 -0
  134. package/types/src/Core/These.d.ts.map +1 -0
  135. package/types/src/Core/Validation.d.ts +213 -0
  136. package/types/src/Core/Validation.d.ts.map +1 -0
  137. package/types/src/Core/index.d.ts +16 -0
  138. package/types/src/Core/index.d.ts.map +1 -0
  139. package/types/src/Types/Brand.d.ts +52 -0
  140. package/types/src/Types/Brand.d.ts.map +1 -0
  141. package/types/src/Types/NonEmptyList.d.ts +29 -0
  142. package/types/src/Types/NonEmptyList.d.ts.map +1 -0
  143. package/types/src/Types/index.d.ts +3 -0
  144. package/types/src/Types/index.d.ts.map +1 -0
@@ -0,0 +1,206 @@
1
+ export var RemoteData;
2
+ (function (RemoteData) {
3
+ /**
4
+ * Creates a NotAsked RemoteData.
5
+ */
6
+ RemoteData.notAsked = () => ({ kind: "NotAsked" });
7
+ /**
8
+ * Creates a Loading RemoteData.
9
+ */
10
+ RemoteData.loading = () => ({ kind: "Loading" });
11
+ /**
12
+ * Creates a Failure RemoteData with the given error.
13
+ */
14
+ RemoteData.failure = (error) => ({
15
+ kind: "Failure",
16
+ error,
17
+ });
18
+ /**
19
+ * Creates a Success RemoteData with the given value.
20
+ */
21
+ RemoteData.success = (value) => ({
22
+ kind: "Success",
23
+ value,
24
+ });
25
+ /**
26
+ * Type guard that checks if a RemoteData is NotAsked.
27
+ */
28
+ RemoteData.isNotAsked = (data) => data.kind === "NotAsked";
29
+ /**
30
+ * Type guard that checks if a RemoteData is Loading.
31
+ */
32
+ RemoteData.isLoading = (data) => data.kind === "Loading";
33
+ /**
34
+ * Type guard that checks if a RemoteData is Failure.
35
+ */
36
+ RemoteData.isFailure = (data) => data.kind === "Failure";
37
+ /**
38
+ * Type guard that checks if a RemoteData is Success.
39
+ */
40
+ RemoteData.isSuccess = (data) => data.kind === "Success";
41
+ /**
42
+ * Transforms the success value inside a RemoteData.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * pipe(RemoteData.success(5), RemoteData.map(n => n * 2)); // Success(10)
47
+ * pipe(RemoteData.loading(), RemoteData.map(n => n * 2)); // Loading
48
+ * ```
49
+ */
50
+ RemoteData.map = (f) => (data) => RemoteData.isSuccess(data) ? RemoteData.success(f(data.value)) : data;
51
+ /**
52
+ * Transforms the error value inside a RemoteData.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * pipe(RemoteData.failure("oops"), RemoteData.mapError(e => e.toUpperCase())); // Failure("OOPS")
57
+ * ```
58
+ */
59
+ RemoteData.mapError = (f) => (data) => RemoteData.isFailure(data) ? RemoteData.failure(f(data.error)) : data;
60
+ /**
61
+ * Chains RemoteData computations. If the input is Success, passes the value to f.
62
+ * Otherwise, propagates the current state.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * pipe(
67
+ * RemoteData.success(5),
68
+ * RemoteData.chain(n => n > 0 ? RemoteData.success(n) : RemoteData.failure("negative"))
69
+ * );
70
+ * ```
71
+ */
72
+ RemoteData.chain = (f) => (data) => RemoteData.isSuccess(data) ? f(data.value) : data;
73
+ /**
74
+ * Applies a function wrapped in a RemoteData to a value wrapped in a RemoteData.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const add = (a: number) => (b: number) => a + b;
79
+ * pipe(
80
+ * RemoteData.success(add),
81
+ * RemoteData.ap(RemoteData.success(5)),
82
+ * RemoteData.ap(RemoteData.success(3))
83
+ * ); // Success(8)
84
+ * ```
85
+ */
86
+ RemoteData.ap = (arg) => (data) => {
87
+ if (RemoteData.isSuccess(data) && RemoteData.isSuccess(arg)) {
88
+ return RemoteData.success(data.value(arg.value));
89
+ }
90
+ if (RemoteData.isFailure(data))
91
+ return data;
92
+ if (RemoteData.isFailure(arg))
93
+ return arg;
94
+ if (RemoteData.isLoading(data) || RemoteData.isLoading(arg))
95
+ return RemoteData.loading();
96
+ return RemoteData.notAsked();
97
+ };
98
+ /**
99
+ * Extracts the value from a RemoteData by providing handlers for all four cases.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * pipe(
104
+ * userData,
105
+ * RemoteData.fold(
106
+ * () => "Not asked",
107
+ * () => "Loading...",
108
+ * e => `Error: ${e}`,
109
+ * value => `Got: ${value}`
110
+ * )
111
+ * );
112
+ * ```
113
+ */
114
+ RemoteData.fold = (onNotAsked, onLoading, onFailure, onSuccess) => (data) => {
115
+ switch (data.kind) {
116
+ case "NotAsked":
117
+ return onNotAsked();
118
+ case "Loading":
119
+ return onLoading();
120
+ case "Failure":
121
+ return onFailure(data.error);
122
+ case "Success":
123
+ return onSuccess(data.value);
124
+ }
125
+ };
126
+ /**
127
+ * Pattern matches on a RemoteData, returning the result of the matching case.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * pipe(
132
+ * userData,
133
+ * RemoteData.match({
134
+ * notAsked: () => "Click to load",
135
+ * loading: () => "Loading...",
136
+ * failure: e => `Error: ${e}`,
137
+ * success: user => `Hello, ${user.name}!`
138
+ * })
139
+ * );
140
+ * ```
141
+ */
142
+ RemoteData.match = (cases) => (data) => {
143
+ switch (data.kind) {
144
+ case "NotAsked":
145
+ return cases.notAsked();
146
+ case "Loading":
147
+ return cases.loading();
148
+ case "Failure":
149
+ return cases.failure(data.error);
150
+ case "Success":
151
+ return cases.success(data.value);
152
+ }
153
+ };
154
+ /**
155
+ * Returns the success value or a default value if the RemoteData is not Success.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * pipe(RemoteData.success(5), RemoteData.getOrElse(0)); // 5
160
+ * pipe(RemoteData.loading(), RemoteData.getOrElse(0)); // 0
161
+ * ```
162
+ */
163
+ RemoteData.getOrElse = (defaultValue) => (data) => RemoteData.isSuccess(data) ? data.value : defaultValue;
164
+ /**
165
+ * Executes a side effect on the success value without changing the RemoteData.
166
+ *
167
+ * @example
168
+ * ```ts
169
+ * pipe(
170
+ * RemoteData.success(5),
171
+ * RemoteData.tap(n => console.log("Value:", n)),
172
+ * RemoteData.map(n => n * 2)
173
+ * );
174
+ * ```
175
+ */
176
+ RemoteData.tap = (f) => (data) => {
177
+ if (RemoteData.isSuccess(data))
178
+ f(data.value);
179
+ return data;
180
+ };
181
+ /**
182
+ * Recovers from a Failure state by providing a fallback RemoteData.
183
+ */
184
+ RemoteData.recover = (fallback) => (data) => RemoteData.isFailure(data) ? fallback(data.error) : data;
185
+ /**
186
+ * Converts a RemoteData to an Option.
187
+ * Success becomes Some, all other states become None.
188
+ */
189
+ RemoteData.toOption = (data) => RemoteData.isSuccess(data) ? { kind: "Some", value: data.value } : { kind: "None" };
190
+ /**
191
+ * Converts a RemoteData to a Result.
192
+ * Success becomes Ok, Failure becomes Err.
193
+ * NotAsked and Loading become Err with the provided fallback error.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * pipe(
198
+ * RemoteData.success(42),
199
+ * RemoteData.toResult(() => "not loaded")
200
+ * ); // Ok(42)
201
+ * ```
202
+ */
203
+ RemoteData.toResult = (onNotReady) => (data) => RemoteData.isSuccess(data)
204
+ ? { kind: "Ok", value: data.value }
205
+ : { kind: "Error", error: RemoteData.isFailure(data) ? data.error : onNotReady() };
206
+ })(RemoteData || (RemoteData = {}));
@@ -0,0 +1,164 @@
1
+ export var Result;
2
+ (function (Result) {
3
+ /**
4
+ * Creates a successful Result with the given value.
5
+ */
6
+ Result.ok = (value) => ({ kind: "Ok", value });
7
+ /**
8
+ * Creates a failed Result with the given error.
9
+ */
10
+ Result.err = (error) => ({ kind: "Error", error });
11
+ /**
12
+ * Type guard that checks if an Result is Ok.
13
+ */
14
+ Result.isOk = (data) => data.kind === "Ok";
15
+ /**
16
+ * Type guard that checks if an Result is Err.
17
+ */
18
+ Result.isErr = (data) => data.kind === "Error";
19
+ /**
20
+ * Creates an Result from a function that may throw.
21
+ * Catches any errors and transforms them using the onError function.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const parseJson = (s: string): Result<string, unknown> =>
26
+ * Result.tryCatch(
27
+ * () => JSON.parse(s),
28
+ * (e) => `Parse error: ${e}`
29
+ * );
30
+ * ```
31
+ */
32
+ Result.tryCatch = (f, onError) => {
33
+ try {
34
+ return Result.ok(f());
35
+ }
36
+ catch (e) {
37
+ return Result.err(onError(e));
38
+ }
39
+ };
40
+ /**
41
+ * Transforms the success value inside an Result.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * pipe(Result.ok(5), Result.map(n => n * 2)); // Ok(10)
46
+ * pipe(Result.err("error"), Result.map(n => n * 2)); // Err("error")
47
+ * ```
48
+ */
49
+ Result.map = (f) => (data) => Result.isOk(data) ? Result.ok(f(data.value)) : data;
50
+ /**
51
+ * Transforms the error value inside an Result.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * pipe(Result.err("oops"), Result.mapError(e => e.toUpperCase())); // Err("OOPS")
56
+ * ```
57
+ */
58
+ Result.mapError = (f) => (data) => Result.isErr(data) ? Result.err(f(data.error)) : data;
59
+ /**
60
+ * Chains Result computations. If the first is Ok, passes the value to f.
61
+ * If the first is Err, propagates the error.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * const validatePositive = (n: number): Result<string, number> =>
66
+ * n > 0 ? Result.ok(n) : Result.err("Must be positive");
67
+ *
68
+ * pipe(Result.ok(5), Result.chain(validatePositive)); // Ok(5)
69
+ * pipe(Result.ok(-1), Result.chain(validatePositive)); // Err("Must be positive")
70
+ * ```
71
+ */
72
+ Result.chain = (f) => (data) => Result.isOk(data) ? f(data.value) : data;
73
+ /**
74
+ * Extracts the value from an Result by providing handlers for both cases.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * pipe(
79
+ * Result.ok(5),
80
+ * Result.fold(
81
+ * e => `Error: ${e}`,
82
+ * n => `Value: ${n}`
83
+ * )
84
+ * ); // "Value: 5"
85
+ * ```
86
+ */
87
+ Result.fold = (onErr, onOk) => (data) => Result.isOk(data) ? onOk(data.value) : onErr(data.error);
88
+ /**
89
+ * Pattern matches on a Result, returning the result of the matching case.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * pipe(
94
+ * result,
95
+ * Result.match({
96
+ * ok: value => `Got ${value}`,
97
+ * err: error => `Failed: ${error}`
98
+ * })
99
+ * );
100
+ * ```
101
+ */
102
+ Result.match = (cases) => (data) => Result.isOk(data) ? cases.ok(data.value) : cases.err(data.error);
103
+ /**
104
+ * Returns the success value or a default value if the Result is an error.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * pipe(Result.ok(5), Result.getOrElse(0)); // 5
109
+ * pipe(Result.err("error"), Result.getOrElse(0)); // 0
110
+ * ```
111
+ */
112
+ Result.getOrElse = (defaultValue) => (data) => Result.isOk(data) ? data.value : defaultValue;
113
+ /**
114
+ * Executes a side effect on the success value without changing the Result.
115
+ * Useful for logging or debugging.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * pipe(
120
+ * Result.ok(5),
121
+ * Result.tap(n => console.log("Value:", n)),
122
+ * Result.map(n => n * 2)
123
+ * );
124
+ * ```
125
+ */
126
+ Result.tap = (f) => (data) => {
127
+ if (Result.isOk(data))
128
+ f(data.value);
129
+ return data;
130
+ };
131
+ /**
132
+ * Recovers from an error by providing a fallback Result.
133
+ */
134
+ Result.recover = (fallback) => (data) => Result.isOk(data) ? data : fallback();
135
+ /**
136
+ * Recovers from an error unless it matches the blocked error.
137
+ */
138
+ Result.recoverUnless = (blockedErr, fallback) => (data) => Result.isErr(data) && data.error !== blockedErr ? fallback() : data;
139
+ /**
140
+ * Converts a Result to an Option.
141
+ * Ok becomes Some, Err becomes None (the error is discarded).
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * Result.toOption(Result.ok(42)); // Some(42)
146
+ * Result.toOption(Result.err("oops")); // None
147
+ * ```
148
+ */
149
+ Result.toOption = (data) => Result.isOk(data) ? { kind: "Some", value: data.value } : { kind: "None" };
150
+ /**
151
+ * Applies a function wrapped in an Result to a value wrapped in an Result.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const add = (a: number) => (b: number) => a + b;
156
+ * pipe(
157
+ * Result.ok(add),
158
+ * Result.ap(Result.ok(5)),
159
+ * Result.ap(Result.ok(3))
160
+ * ); // Ok(8)
161
+ * ```
162
+ */
163
+ Result.ap = (arg) => (data) => Result.isOk(data) && Result.isOk(arg) ? Result.ok(data.value(arg.value)) : Result.isErr(data) ? data : arg;
164
+ })(Result || (Result = {}));
@@ -0,0 +1,187 @@
1
+ import { Deferred } from "./Deferred.js";
2
+ import { Result } from "./Result.js";
3
+ // Internal helper — not exported. Runs a Task and converts the result to a Promise
4
+ // so that combinators can use Promise chaining (.then, Promise.all, Promise.race, etc.)
5
+ // internally without leaking that primitive through the public API.
6
+ const toPromise = (task) => Deferred.toPromise(task());
7
+ export var Task;
8
+ (function (Task) {
9
+ /**
10
+ * Creates a Task that immediately resolves to the given value.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const task = Task.resolve(42);
15
+ * const value = await task(); // 42
16
+ * ```
17
+ */
18
+ Task.resolve = (value) => () => Deferred.fromPromise(Promise.resolve(value));
19
+ /**
20
+ * Creates a Task from a function that returns a Promise.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const getTimestamp = Task.from(() => Promise.resolve(Date.now()));
25
+ * ```
26
+ */
27
+ Task.from = (f) => () => Deferred.fromPromise(f());
28
+ /**
29
+ * Transforms the value inside a Task.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * pipe(
34
+ * Task.resolve(5),
35
+ * Task.map(n => n * 2)
36
+ * )(); // Deferred<10>
37
+ * ```
38
+ */
39
+ Task.map = (f) => (data) => Task.from(() => toPromise(data).then(f));
40
+ /**
41
+ * Chains Task computations. Passes the resolved value of the first Task to f.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * const readUserId: Task<string> = Task.resolve(session.userId);
46
+ * const loadPrefs = (id: string): Task<Preferences> =>
47
+ * Task.resolve(prefsCache.get(id));
48
+ *
49
+ * pipe(
50
+ * readUserId,
51
+ * Task.chain(loadPrefs)
52
+ * )(); // Deferred<Preferences>
53
+ * ```
54
+ */
55
+ Task.chain = (f) => (data) => Task.from(() => toPromise(data).then((a) => toPromise(f(a))));
56
+ /**
57
+ * Applies a function wrapped in a Task to a value wrapped in a Task.
58
+ * Both Tasks run in parallel.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * const add = (a: number) => (b: number) => a + b;
63
+ * pipe(
64
+ * Task.resolve(add),
65
+ * Task.ap(Task.resolve(5)),
66
+ * Task.ap(Task.resolve(3))
67
+ * )(); // Deferred<8>
68
+ * ```
69
+ */
70
+ Task.ap = (arg) => (data) => Task.from(() => Promise.all([
71
+ toPromise(data),
72
+ toPromise(arg),
73
+ ]).then(([f, a]) => f(a)));
74
+ /**
75
+ * Executes a side effect on the value without changing the Task.
76
+ * Useful for logging or debugging.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * pipe(
81
+ * loadConfig,
82
+ * Task.tap(cfg => console.log("Config:", cfg)),
83
+ * Task.map(buildReport)
84
+ * );
85
+ * ```
86
+ */
87
+ Task.tap = (f) => (data) => Task.from(() => toPromise(data).then((a) => {
88
+ f(a);
89
+ return a;
90
+ }));
91
+ /**
92
+ * Runs multiple Tasks in parallel and collects their results.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * Task.all([loadConfig, detectLocale, loadTheme])();
97
+ * // Deferred<[Config, string, Theme]>
98
+ * ```
99
+ */
100
+ Task.all = (tasks) => Task.from(() => Promise.all(tasks.map((t) => toPromise(t))));
101
+ /**
102
+ * Delays the execution of a Task by the specified milliseconds.
103
+ * Useful for debouncing or rate limiting.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * pipe(
108
+ * Task.resolve(42),
109
+ * Task.delay(1000)
110
+ * )(); // Resolves after 1 second
111
+ * ```
112
+ */
113
+ Task.delay = (ms) => (data) => Task.from(() => new Promise((resolve) => setTimeout(() => toPromise(data).then(resolve), ms)));
114
+ /**
115
+ * Runs a Task a fixed number of times sequentially, collecting all results into an array.
116
+ * An optional delay (ms) can be inserted between runs.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * pipe(
121
+ * pollSensor,
122
+ * Task.repeat({ times: 5, delay: 1000 })
123
+ * )(); // Task<Reading[]> — 5 readings, one per second
124
+ * ```
125
+ */
126
+ Task.repeat = (options) => (task) => Task.from(() => {
127
+ const { times, delay: ms } = options;
128
+ if (times <= 0)
129
+ return Promise.resolve([]);
130
+ const results = [];
131
+ const wait = () => ms !== undefined && ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve();
132
+ const run = (left) => toPromise(task).then((a) => {
133
+ results.push(a);
134
+ if (left <= 1)
135
+ return results;
136
+ return wait().then(() => run(left - 1));
137
+ });
138
+ return run(times);
139
+ });
140
+ /**
141
+ * Runs a Task repeatedly until the result satisfies a predicate, returning that result.
142
+ * An optional delay (ms) can be inserted between runs.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * pipe(
147
+ * checkStatus,
148
+ * Task.repeatUntil({ when: (s) => s === "ready", delay: 500 })
149
+ * )(); // polls every 500ms until status is "ready"
150
+ * ```
151
+ */
152
+ Task.repeatUntil = (options) => (task) => Task.from(() => {
153
+ const { when: predicate, delay: ms } = options;
154
+ const wait = () => ms !== undefined && ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve();
155
+ const run = () => toPromise(task).then((a) => {
156
+ if (predicate(a))
157
+ return a;
158
+ return wait().then(run);
159
+ });
160
+ return run();
161
+ });
162
+ /**
163
+ * Converts a `Task<A>` into a `Task<Result<E, A>>`, resolving to `Err` if the
164
+ * Task does not complete within the given time.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * pipe(
169
+ * heavyComputation,
170
+ * Task.timeout(5000, () => "timed out"),
171
+ * TaskResult.chain(processResult)
172
+ * );
173
+ * ```
174
+ */
175
+ Task.timeout = (ms, onTimeout) => (task) => Task.from(() => {
176
+ let timerId;
177
+ return Promise.race([
178
+ toPromise(task).then((a) => {
179
+ clearTimeout(timerId);
180
+ return Result.ok(a);
181
+ }),
182
+ new Promise((resolve) => {
183
+ timerId = setTimeout(() => resolve(Result.err(onTimeout())), ms);
184
+ }),
185
+ ]);
186
+ });
187
+ })(Task || (Task = {}));
@@ -0,0 +1,105 @@
1
+ import { Deferred } from "./Deferred.js";
2
+ import { Option } from "./Option.js";
3
+ import { Task } from "./Task.js";
4
+ export var TaskOption;
5
+ (function (TaskOption) {
6
+ /**
7
+ * Wraps a value in a Some inside a Task.
8
+ */
9
+ TaskOption.some = (value) => Task.resolve(Option.some(value));
10
+ /**
11
+ * Creates a TaskOption that resolves to None.
12
+ */
13
+ TaskOption.none = () => Task.resolve(Option.none());
14
+ /**
15
+ * Lifts an Option into a TaskOption.
16
+ */
17
+ TaskOption.fromOption = (option) => Task.resolve(option);
18
+ /**
19
+ * Lifts a Task into a TaskOption by wrapping its result in Some.
20
+ */
21
+ TaskOption.fromTask = (task) => Task.map(Option.some)(task);
22
+ /**
23
+ * Creates a TaskOption from a Promise-returning function.
24
+ * Returns Some if the promise resolves, None if it rejects.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const fetchUser = TaskOption.tryCatch(() =>
29
+ * fetch("/user/1").then(r => r.json())
30
+ * );
31
+ * ```
32
+ */
33
+ TaskOption.tryCatch = (f) => Task.from(() => f()
34
+ .then(Option.some)
35
+ .catch(() => Option.none()));
36
+ /**
37
+ * Transforms the value inside a TaskOption.
38
+ */
39
+ TaskOption.map = (f) => (data) => Task.map(Option.map(f))(data);
40
+ /**
41
+ * Chains TaskOption computations. If the first resolves to Some, passes the
42
+ * value to f. If the first resolves to None, propagates None.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * pipe(
47
+ * findUser("123"),
48
+ * TaskOption.chain(user => findOrg(user.orgId))
49
+ * )();
50
+ * ```
51
+ */
52
+ TaskOption.chain = (f) => (data) => Task.chain((option) => Option.isSome(option) ? f(option.value) : Task.resolve(Option.none()))(data);
53
+ /**
54
+ * Applies a function wrapped in a TaskOption to a value wrapped in a TaskOption.
55
+ * Both Tasks run in parallel.
56
+ */
57
+ TaskOption.ap = (arg) => (data) => Task.from(() => Promise.all([
58
+ Deferred.toPromise(data()),
59
+ Deferred.toPromise(arg()),
60
+ ]).then(([of_, oa]) => Option.ap(oa)(of_)));
61
+ /**
62
+ * Extracts a value from a TaskOption by providing handlers for both cases.
63
+ */
64
+ TaskOption.fold = (onNone, onSome) => (data) => Task.map(Option.fold(onNone, onSome))(data);
65
+ /**
66
+ * Pattern matches on a TaskOption, returning a Task of the result.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * pipe(
71
+ * findUser("123"),
72
+ * TaskOption.match({
73
+ * some: user => `Hello, ${user.name}`,
74
+ * none: () => "User not found"
75
+ * })
76
+ * )();
77
+ * ```
78
+ */
79
+ TaskOption.match = (cases) => (data) => Task.map(Option.match(cases))(data);
80
+ /**
81
+ * Returns the value or a default if the TaskOption resolves to None.
82
+ */
83
+ TaskOption.getOrElse = (defaultValue) => (data) => Task.map(Option.getOrElse(defaultValue))(data);
84
+ /**
85
+ * Executes a side effect on the value without changing the TaskOption.
86
+ * Useful for logging or debugging.
87
+ */
88
+ TaskOption.tap = (f) => (data) => Task.map(Option.tap(f))(data);
89
+ /**
90
+ * Filters the value inside a TaskOption. Returns None if the predicate fails.
91
+ */
92
+ TaskOption.filter = (predicate) => (data) => Task.map(Option.filter(predicate))(data);
93
+ /**
94
+ * Converts a TaskOption to a TaskResult, using onNone to produce the error value.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * pipe(
99
+ * findUser("123"),
100
+ * TaskOption.toTaskResult(() => "User not found")
101
+ * );
102
+ * ```
103
+ */
104
+ TaskOption.toTaskResult = (onNone) => (data) => Task.map(Option.toResult(onNone))(data);
105
+ })(TaskOption || (TaskOption = {}));