@shirudo/result 0.0.1 → 0.0.3
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.
- package/README.md +99 -1
- package/dist/index.cjs +487 -942
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +390 -807
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +390 -807
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +485 -942
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -10
package/README.md
CHANGED
|
@@ -146,6 +146,21 @@ const calculate = task(function* () {
|
|
|
146
146
|
// calculate is a Promise<Result<number, Error>>
|
|
147
147
|
```
|
|
148
148
|
|
|
149
|
+
#### Error Handling with `onThrow`
|
|
150
|
+
|
|
151
|
+
The `task()` function accepts an optional `onThrow` callback for custom error mapping:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const result = await task(
|
|
155
|
+
function* () {
|
|
156
|
+
const data = yield* fetchData();
|
|
157
|
+
return process(data);
|
|
158
|
+
},
|
|
159
|
+
(error) => new CustomError(`Failed: ${error}`) // custom error mapping
|
|
160
|
+
);
|
|
161
|
+
// Returns Result<ProcessedData, CustomError>
|
|
162
|
+
```
|
|
163
|
+
|
|
149
164
|
### Folding Results
|
|
150
165
|
|
|
151
166
|
The simplest way to handle both `Ok` and `Err` cases and return a single value:
|
|
@@ -195,6 +210,19 @@ const message = result
|
|
|
195
210
|
.run();
|
|
196
211
|
```
|
|
197
212
|
|
|
213
|
+
#### Async Pattern Matching
|
|
214
|
+
|
|
215
|
+
For async handlers, use `matchAsync`:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
import { matchAsync } from "@shirudo/result";
|
|
219
|
+
|
|
220
|
+
const result = await matchAsync({
|
|
221
|
+
ok: async (val) => `Success: ${val}`,
|
|
222
|
+
err: async (e) => `Error: ${e}`
|
|
223
|
+
})(someResult);
|
|
224
|
+
```
|
|
225
|
+
|
|
198
226
|
**When to use what:**
|
|
199
227
|
|
|
200
228
|
- Use `.fold()` for simple cases where you handle both Ok and Err
|
|
@@ -208,6 +236,8 @@ const message = result
|
|
|
208
236
|
### Creation & Conversions
|
|
209
237
|
|
|
210
238
|
- `ok(value)` / `err(error)`: Create basic instances.
|
|
239
|
+
- `okIf(condition, okValue, errValue)`: Conditionally create `Ok` or `Err`.
|
|
240
|
+
- `okIfLazy(condition, okFn, errFn)`: Lazy conditional creation.
|
|
211
241
|
- `Result.try(fn)`: Execute a sync function; catches exceptions as `Err`.
|
|
212
242
|
- `Result.fromNullable(val, fallback)`: Convert `null | undefined` to `Err`.
|
|
213
243
|
- `Result.fromPromise(promise)`: Convert a Promise to `Promise<Result>`.
|
|
@@ -222,12 +252,41 @@ const message = result
|
|
|
222
252
|
- `.unwrapErr()`: Get error or throw (use carefully).
|
|
223
253
|
- `.unwrapOr(default)`: Get value or return default.
|
|
224
254
|
- `.unwrapOrElse(fn)`: Get value or generate default from error.
|
|
255
|
+
- `.unwrapOrThrow()`: Get value or throw original error (preserves stack trace).
|
|
225
256
|
- `.expect(msg)`: Get value or throw with specific message.
|
|
226
257
|
- `.expectErr(msg)`: Get error or throw with specific message.
|
|
227
258
|
- `.fold(onOk, onErr)`: Handle both cases and return a single value.
|
|
228
259
|
- `.pipe(...)`: Chain operators synchronously.
|
|
229
260
|
- `.pipeAsync(...)`: Chain operators asynchronously.
|
|
230
|
-
- `.match()`: Start a fluent pattern matching builder.
|
|
261
|
+
- `.match()`: Start a fluent pattern matching builder (Err only).
|
|
262
|
+
- `.matchErr()`: Pattern matching builder for Err cases.
|
|
263
|
+
- `.serialize()`: Convert to `{ isSuccess, data?, error? }`.
|
|
264
|
+
- `.toUserFriendly()`: User-friendly serialization with error messages.
|
|
265
|
+
|
|
266
|
+
### Utilities
|
|
267
|
+
|
|
268
|
+
Type guards and helper functions:
|
|
269
|
+
|
|
270
|
+
- `isResult(value)`: Type guard to check if a value is a `Result`.
|
|
271
|
+
- `contains(result, value)`: Check if `Ok` contains a specific value.
|
|
272
|
+
- `containsErr(result, error)`: Check if `Err` contains a specific error.
|
|
273
|
+
- `fromResult(fn)`: Execute a function, catching exceptions (Rust `Result::from`).
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { isResult, contains, containsErr, fromResult, ok, err } from "@shirudo/result";
|
|
277
|
+
|
|
278
|
+
isResult(ok(5)); // true
|
|
279
|
+
isResult("not a result"); // false
|
|
280
|
+
|
|
281
|
+
const result = ok(42);
|
|
282
|
+
contains(result, 42); // true
|
|
283
|
+
contains(result, 100); // false
|
|
284
|
+
|
|
285
|
+
const errResult = err("not found");
|
|
286
|
+
containsErr(errResult, "not found"); // true
|
|
287
|
+
|
|
288
|
+
const wrapped = fromResult(() => JSON.parse('{"valid": true}'));
|
|
289
|
+
```
|
|
231
290
|
|
|
232
291
|
### Pipeable Operators
|
|
233
292
|
|
|
@@ -248,11 +307,50 @@ Import these from the root package to use inside `.pipe()`.
|
|
|
248
307
|
|
|
249
308
|
**Async Variants:** `mapAsync`, `mapErrAsync`, `flatMapAsync`, `filterAsync`, `tapAsync`, `tryCatchAsync`, `tryMapAsync`, `foldAsync`.
|
|
250
309
|
|
|
310
|
+
### Combinators
|
|
311
|
+
|
|
312
|
+
Combinators (inspired by Rust) for composing and transforming Results:
|
|
313
|
+
|
|
314
|
+
| Combinator | Description |
|
|
315
|
+
| :--------- | :---------- |
|
|
316
|
+
| `and(r1, r2)` | Short-circuit AND: returns `r2` only if `r1` is `Ok` |
|
|
317
|
+
| `or(r1, r2)` | Returns `r1` if `Ok`, otherwise `r2` |
|
|
318
|
+
| `orElse(r, fn)` | Returns `r` if `Ok`, otherwise calls `fn(error)` |
|
|
319
|
+
| `mapOr(r, default, fn)` | Maps `Ok` value or returns `default` |
|
|
320
|
+
| `mapOrElse(r, defaultFn, fn)` | Maps `Ok` value or computes `default` from error |
|
|
321
|
+
| `swap(r)` | Swaps Ok and Err: `Result<T, E>` → `Result<E, T>` |
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
import { and, or, orElse, mapOr, mapOrElse, swap, ok, err } from "@shirudo/result";
|
|
325
|
+
|
|
326
|
+
const a = ok(5);
|
|
327
|
+
const b = ok(10);
|
|
328
|
+
|
|
329
|
+
// and: returns b only if a is Ok
|
|
330
|
+
and(a, b); // Ok(10)
|
|
331
|
+
|
|
332
|
+
// or: returns first Ok, otherwise fallback
|
|
333
|
+
or(err("fallback"), ok("success")); // Ok("success")
|
|
334
|
+
|
|
335
|
+
// orElse: lazy fallback with error context
|
|
336
|
+
orElse(err("error"), (e) => ok(`recovered: ${e}`)); // Ok("recovered: error")
|
|
337
|
+
|
|
338
|
+
// mapOr: map or use default
|
|
339
|
+
mapOr(ok(5), 0, (n) => n * 2); // 10
|
|
340
|
+
mapOr(err("x"), 0, (n) => n * 2); // 0
|
|
341
|
+
|
|
342
|
+
// swap: interchange Ok and Err
|
|
343
|
+
swap(ok("value")); // Err("value")
|
|
344
|
+
swap(err("error")); // Ok("error")
|
|
345
|
+
```
|
|
346
|
+
|
|
251
347
|
### Collections
|
|
252
348
|
|
|
253
349
|
- `sequence(results)`: Turn `Result[]` into `Result<T[]>`. First error stops the process.
|
|
254
350
|
- `sequenceRecord(record)`: Like `sequence`, but for objects (`{ a: Result, b: Result }` → `Result<{ a, b }>`).
|
|
255
351
|
- `collectFirstOk(results)`: Find the first success, or return all errors.
|
|
352
|
+
- `collectFirstOkAsync(results)`: Async version - find the first success.
|
|
353
|
+
- `collectFirstOkParallelAsync(results)`: Parallel variant - first success wins, all rejections continue.
|
|
256
354
|
- `collectAllErrors(results)`: Returns `Ok(values)` only if all are Ok, otherwise collects _all_ errors.
|
|
257
355
|
- `partition(results)`: Separate a list into arrays of `[oks, errs]`.
|
|
258
356
|
- `flatten(result)`: Flattens a nested `Result<Result<T, E>, E>` into `Result<T, E>`.
|