@eserstack/primitives 0.0.0-bootstrap.0 → 5.0.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.
- package/LICENSE +13 -0
- package/README.md +148 -0
- package/dist/functions.d.ts +45 -0
- package/dist/functions.js +17 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +22 -0
- package/dist/options.d.ts +105 -0
- package/dist/options.js +142 -0
- package/dist/promises.d.ts +21 -0
- package/dist/promises.js +2 -0
- package/dist/results.d.ts +131 -0
- package/dist/results.js +153 -0
- package/dist/type-guards.d.ts +66 -0
- package/dist/type-guards.js +78 -0
- package/dist/type-slices.d.ts +35 -0
- package/dist/type-slices.js +2 -0
- package/package.json +51 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2023-present Eser Ozvataf and other contributors.
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# 🧱 [@eserstack/primitives](./)
|
|
2
|
+
|
|
3
|
+
> **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/primitives` is
|
|
4
|
+
> published on npm under the same name (`pnpm add @eserstack/primitives`); the
|
|
5
|
+
> JSR versions stay available but get no updates.
|
|
6
|
+
|
|
7
|
+
> **eserstack Foundation** —
|
|
8
|
+
> [eser/stack on GitHub](https://github.com/eser/stack) **Install:**
|
|
9
|
+
> `pnpm add @eserstack/primitives`
|
|
10
|
+
|
|
11
|
+
The type foundation for the eserstack FP ecosystem.
|
|
12
|
+
|
|
13
|
+
## Vision
|
|
14
|
+
|
|
15
|
+
`@eserstack/primitives` defines the `Result` and `Option` types that the rest of
|
|
16
|
+
the ecosystem passes around, the functions that create, inspect and combine
|
|
17
|
+
them, and runtime type guards and type-level helpers. Every other package in the
|
|
18
|
+
ecosystem builds on these primitives.
|
|
19
|
+
|
|
20
|
+
## Design Philosophy
|
|
21
|
+
|
|
22
|
+
- **Types describe shapes.** `Result<T, E>`, `Option<T>`, `Ok<T>`, `Fail<E>`,
|
|
23
|
+
`Some<T>`, `None` — discriminated unions with a `_tag` field.
|
|
24
|
+
- **Constructors create values.** `ok()`, `fail()`, `some()`, `none` — minimal
|
|
25
|
+
factory functions.
|
|
26
|
+
- **Type guards narrow them.** `isOk()`, `isFail()`, `isSome()`, `isNone()` —
|
|
27
|
+
predicate functions for type narrowing.
|
|
28
|
+
- **Combinators live next to their type.** `primitives.results` also exports
|
|
29
|
+
`map`, `flatMap`, `mapError`, `match`, `getOrElse`, `tryCatch`, `all`, `any`
|
|
30
|
+
and `tap`, and `primitives.options` exports `map`, `flatMap`, `filter`,
|
|
31
|
+
`match`, `orElse`, `zip` and `toResult`. Each takes the result or option as
|
|
32
|
+
its first argument; to chain them in `fp.pipe`, wrap each call in an arrow
|
|
33
|
+
function, as in `(result) => primitives.results.map(result, double)`.
|
|
34
|
+
- **General utilities live elsewhere.** Functions over arrays, objects and other
|
|
35
|
+
functions (`pipe`, `flow`, `groupBy`, `deepMerge` and the rest) are in
|
|
36
|
+
[`@eserstack/fp`](../fp/), and multi-step workflows are in
|
|
37
|
+
[`@eserstack/functions`](../functions/).
|
|
38
|
+
|
|
39
|
+
## How It Fits
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
@eserstack/primitives → @eserstack/fp → @eserstack/functions
|
|
43
|
+
(this package) (array, object (higher-level
|
|
44
|
+
types, and function compositions)
|
|
45
|
+
constructors, utilities)
|
|
46
|
+
combinators)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- **vs `@eserstack/fp`**: Primitives defines `Result<T, E>` and the `map`,
|
|
50
|
+
`flatMap` and `match` that work on it; fp gives you `pipe` and `flow`, which
|
|
51
|
+
chain one-argument functions such as those calls wrapped in arrow functions,
|
|
52
|
+
plus utilities for arrays and objects.
|
|
53
|
+
- **vs `@eserstack/functions`**: Primitives defines the data types — functions
|
|
54
|
+
provides multi-step workflows (`run()`, `collect()`, `Task`) that orchestrate
|
|
55
|
+
them.
|
|
56
|
+
|
|
57
|
+
## Quick Start
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import * as primitives from "@eserstack/primitives";
|
|
61
|
+
|
|
62
|
+
// Result — explicit error handling
|
|
63
|
+
const divide = (
|
|
64
|
+
a: number,
|
|
65
|
+
b: number,
|
|
66
|
+
): primitives.results.Result<number, string> =>
|
|
67
|
+
b === 0
|
|
68
|
+
? primitives.results.fail("Division by zero")
|
|
69
|
+
: primitives.results.ok(a / b);
|
|
70
|
+
|
|
71
|
+
const result = divide(10, 2);
|
|
72
|
+
if (primitives.results.isOk(result)) {
|
|
73
|
+
console.log(result.value); // 5
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Option — nullable value handling
|
|
77
|
+
const find = (id: string): primitives.options.Option<string> =>
|
|
78
|
+
id === "1" ? primitives.options.some("Alice") : primitives.options.none;
|
|
79
|
+
|
|
80
|
+
const user = find("1");
|
|
81
|
+
if (primitives.options.isSome(user)) {
|
|
82
|
+
console.log(user.value); // "Alice"
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Combinators
|
|
87
|
+
|
|
88
|
+
Each combinator takes the result or option as its first argument. A failure or a
|
|
89
|
+
missing value passes through `map` and `flatMap` untouched, and `match` or
|
|
90
|
+
`getOrElse` turns the outcome into a plain value:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import * as primitives from "@eserstack/primitives";
|
|
94
|
+
|
|
95
|
+
const parsed = primitives.results.tryCatch(() => JSON.parse('{"port":8080}'));
|
|
96
|
+
const port = primitives.results.map(parsed, (config) => Number(config.port));
|
|
97
|
+
const message = primitives.results.match(port, {
|
|
98
|
+
ok: (value) => `listening on ${value}`,
|
|
99
|
+
fail: (error) => `bad config: ${String(error)}`,
|
|
100
|
+
});
|
|
101
|
+
// "listening on 8080"
|
|
102
|
+
|
|
103
|
+
const nicknames = new Map([["ada", "Countess"]]);
|
|
104
|
+
const label = primitives.options.getOrElse(
|
|
105
|
+
primitives.options.map(
|
|
106
|
+
primitives.options.fromNullable(nicknames.get("grace")),
|
|
107
|
+
(value) => value.toUpperCase(),
|
|
108
|
+
),
|
|
109
|
+
"ANONYMOUS",
|
|
110
|
+
);
|
|
111
|
+
// "ANONYMOUS"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Generator Protocol (Do-Notation)
|
|
115
|
+
|
|
116
|
+
`Result` values implement the iterator protocol, enabling `yield*` unwrapping in
|
|
117
|
+
generator-based composition (see `@eserstack/functions`):
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
import * as primitives from "@eserstack/primitives";
|
|
121
|
+
import * as functions from "@eserstack/functions";
|
|
122
|
+
|
|
123
|
+
const result = await functions.run(async function* () {
|
|
124
|
+
const a = yield* primitives.results.ok(5); // unwraps to 5
|
|
125
|
+
const b = yield* primitives.results.ok(10); // unwraps to 10
|
|
126
|
+
return a + b; // 15
|
|
127
|
+
});
|
|
128
|
+
// result: ok(15)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Exports
|
|
132
|
+
|
|
133
|
+
Each module is a namespace on the package root (`primitives.results`,
|
|
134
|
+
`primitives.options` and so on) and is also published under its own sub-path.
|
|
135
|
+
|
|
136
|
+
| Namespace | Sub-path | Contents |
|
|
137
|
+
| ----------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
138
|
+
| `primitives.results` | `@eserstack/primitives/results` | `Result<T,E>`, `Ok<T>`, `Fail<E>`, `ok()`, `fail()`, `isOk()`, `isFail()`; combinators `map`, `flatMap`, `flatMapW`, `mapError`, `flatMapError`, `flatMapErrorW`, `match`, `tap`, `tapError`; `getOrElse`, `getOrThrow`, `getOrNull`, `getOrUndefined`; `all`, `any`; `tryCatch`, `tryCatchAsync`, `fromPromise`, `toPromise` |
|
|
139
|
+
| `primitives.options` | `@eserstack/primitives/options` | `Option<T>`, `Some<T>`, `None`, `some()`, `none`, `isSome()`, `isNone()`, `fromNullable()`, `fromFalsy()`; combinators `map`, `flatMap`, `filter`, `match`, `orElse`, `tap`, `tapNone`, `zip`, `zipWith`, `contains`, `exists`; `getOrElse`, `getOrThrow`, `getOrNull`, `getOrUndefined`; `all`, `any`; `toResult`, `fromResult` |
|
|
140
|
+
| `primitives.functions` | `@eserstack/primitives/functions` | Generic function and class type definitions |
|
|
141
|
+
| `primitives.promises` | `@eserstack/primitives/promises` | `Promisable<T>` and promise utility types |
|
|
142
|
+
| `primitives.typeGuards` | `@eserstack/primitives/type-guards` | Runtime type guards (`isString`, `isNumber`, `isDefined`, etc.) |
|
|
143
|
+
| `primitives.typeSlices` | `@eserstack/primitives/type-slices` | Tuple utility types (`First`, `Last`, `ArgList`, etc.) |
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
🔗 For further details, visit the
|
|
148
|
+
[eserstack repository](https://github.com/eser/stack).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Function and constructor signatures, no-op functions of each kind, and the
|
|
3
|
+
* constructors of those kinds, which `globalThis` does not expose.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import * as primitives from "@eserstack/primitives";
|
|
8
|
+
*
|
|
9
|
+
* const handler = async (): Promise<void> => {};
|
|
10
|
+
* const isAsync = handler instanceof primitives.functions.AsyncFunction;
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
/** A read-only argument list whose items are all `T`. */
|
|
16
|
+
export type ArgList<T> = ReadonlyArray<T>;
|
|
17
|
+
/** A function that takes arguments of type `TP` and returns `TR`. */
|
|
18
|
+
export type GenericFunction<TR, TP> = (...args: ArgList<TP>) => TR;
|
|
19
|
+
/** A class whose constructor takes arguments of type `TP` and builds `TC`. */
|
|
20
|
+
export type GenericClass<TC, TP> = new (...args: ArgList<TP>) => TC;
|
|
21
|
+
/**
|
|
22
|
+
* The constructor of one kind of function: called with or without `new`, it
|
|
23
|
+
* takes parameter names and a body source and builds a function `TF`.
|
|
24
|
+
*/
|
|
25
|
+
export type FunctionKindConstructor<TF> = {
|
|
26
|
+
new (...args: ArgList<string>): TF;
|
|
27
|
+
(...args: ArgList<string>): TF;
|
|
28
|
+
readonly prototype: TF;
|
|
29
|
+
};
|
|
30
|
+
/** An async generator function that yields nothing. */
|
|
31
|
+
export declare const nullAsyncGeneratorFn: <TR>() => AsyncGenerator<TR>;
|
|
32
|
+
/** The constructor of async generator functions (`AsyncGeneratorFunction`). */
|
|
33
|
+
export declare const AsyncGeneratorFunction: FunctionKindConstructor<(...args: ArgList<unknown>) => AsyncGenerator<unknown>>;
|
|
34
|
+
/** A generator function that yields nothing. */
|
|
35
|
+
export declare const nullGeneratorFn: <TR>() => Generator<TR>;
|
|
36
|
+
/** The constructor of generator functions (`GeneratorFunction`). */
|
|
37
|
+
export declare const GeneratorFunction: FunctionKindConstructor<(...args: ArgList<unknown>) => Generator<unknown>>;
|
|
38
|
+
/** An async function that resolves to `undefined`. */
|
|
39
|
+
export declare const nullAsyncFn: <TR = void>() => Promise<TR | void>;
|
|
40
|
+
/** The constructor of async functions (`AsyncFunction`). */
|
|
41
|
+
export declare const AsyncFunction: FunctionKindConstructor<(...args: ArgList<unknown>) => Promise<unknown>>;
|
|
42
|
+
/** A function that returns `undefined`. */
|
|
43
|
+
export declare const nullFn: <TR = void>() => TR | void;
|
|
44
|
+
/** The `Function` constructor, `globalThis.Function`. */
|
|
45
|
+
export declare const Function: FunctionConstructor;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/** An async generator function that yields nothing. */
|
|
3
|
+
export const nullAsyncGeneratorFn = async function* () { };
|
|
4
|
+
/** The constructor of async generator functions (`AsyncGeneratorFunction`). */
|
|
5
|
+
export const AsyncGeneratorFunction = nullAsyncGeneratorFn.constructor;
|
|
6
|
+
/** A generator function that yields nothing. */
|
|
7
|
+
export const nullGeneratorFn = function* () { };
|
|
8
|
+
/** The constructor of generator functions (`GeneratorFunction`). */
|
|
9
|
+
export const GeneratorFunction = nullGeneratorFn.constructor;
|
|
10
|
+
/** An async function that resolves to `undefined`. */
|
|
11
|
+
export const nullAsyncFn = async () => { };
|
|
12
|
+
/** The constructor of async functions (`AsyncFunction`). */
|
|
13
|
+
export const AsyncFunction = nullAsyncFn.constructor;
|
|
14
|
+
/** A function that returns `undefined`. */
|
|
15
|
+
export const nullFn = () => { };
|
|
16
|
+
/** The `Function` constructor, `globalThis.Function`. */
|
|
17
|
+
export const Function = globalThis.Function;
|
package/dist/mod.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The type foundation of eserstack: the `Result` and `Option` types with their
|
|
3
|
+
* constructors, type guards and combinators, runtime type guards, and
|
|
4
|
+
* type-level helpers. Each module is a namespace of this entry point.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import * as primitives from "@eserstack/primitives";
|
|
9
|
+
*
|
|
10
|
+
* const result = primitives.results.tryCatch(() => JSON.parse("{}"));
|
|
11
|
+
* const config = primitives.results.getOrElse(result, {});
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
export * as functions from "./functions.ts";
|
|
17
|
+
export * as options from "./options.ts";
|
|
18
|
+
export * as promises from "./promises.ts";
|
|
19
|
+
export * as results from "./results.ts";
|
|
20
|
+
export * as typeGuards from "./type-guards.ts";
|
|
21
|
+
export * as typeSlices from "./type-slices.ts";
|
package/dist/mod.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* The type foundation of eserstack: the `Result` and `Option` types with their
|
|
4
|
+
* constructors, type guards and combinators, runtime type guards, and
|
|
5
|
+
* type-level helpers. Each module is a namespace of this entry point.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as primitives from "@eserstack/primitives";
|
|
10
|
+
*
|
|
11
|
+
* const result = primitives.results.tryCatch(() => JSON.parse("{}"));
|
|
12
|
+
* const config = primitives.results.getOrElse(result, {});
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
export * as functions from "./functions.js";
|
|
18
|
+
export * as options from "./options.js";
|
|
19
|
+
export * as promises from "./promises.js";
|
|
20
|
+
export * as results from "./results.js";
|
|
21
|
+
export * as typeGuards from "./type-guards.js";
|
|
22
|
+
export * as typeSlices from "./type-slices.js";
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Option type: a value that is either present (`Some`) or absent (`None`),
|
|
3
|
+
* with its constructors, type guards and combinators.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import * as primitives from "@eserstack/primitives";
|
|
8
|
+
*
|
|
9
|
+
* const env: Record<string, string | undefined> = { PORT: "8080" };
|
|
10
|
+
* const port = primitives.options.fromNullable(env["PORT"]);
|
|
11
|
+
*
|
|
12
|
+
* const value = primitives.options.getOrElse(
|
|
13
|
+
* primitives.options.map(port, Number),
|
|
14
|
+
* 3000,
|
|
15
|
+
* );
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import * as results from "./results.ts";
|
|
21
|
+
/** Either a present value (`Some<T>`) or no value (`None`). */
|
|
22
|
+
export type Option<T> = Some<T> | None;
|
|
23
|
+
/** An option that holds a value. Build one with `some()`. */
|
|
24
|
+
export interface Some<T> {
|
|
25
|
+
/** The discriminant that marks a present value; `isSome()` checks it. */
|
|
26
|
+
readonly _tag: "Some";
|
|
27
|
+
/** The value the option holds. */
|
|
28
|
+
readonly value: T;
|
|
29
|
+
}
|
|
30
|
+
/** An option that holds no value. Use the `none` constant. */
|
|
31
|
+
export interface None {
|
|
32
|
+
/** The discriminant that marks an absent value; `isNone()` checks it. */
|
|
33
|
+
readonly _tag: "None";
|
|
34
|
+
}
|
|
35
|
+
/** Wraps `value` in an option that holds it. */
|
|
36
|
+
export declare const some: <T>(value: T) => Some<T>;
|
|
37
|
+
/** The option that holds no value. */
|
|
38
|
+
export declare const none: None;
|
|
39
|
+
/** Returns true when `option` holds a value, and narrows it to `Some<T>`. */
|
|
40
|
+
export declare const isSome: <T>(option: Option<T>) => option is Some<T>;
|
|
41
|
+
/** Returns true when `option` holds no value, and narrows it to `None`. */
|
|
42
|
+
export declare const isNone: <T>(option: Option<T>) => option is None;
|
|
43
|
+
/** Returns `none` for `null` or `undefined`, and `some(value)` otherwise. */
|
|
44
|
+
export declare const fromNullable: <T>(value: T | null | undefined) => Option<T>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns `none` for a falsy value, such as `null`, `undefined`, `false`, `0`
|
|
47
|
+
* or `""`, and `some(value)` otherwise.
|
|
48
|
+
*/
|
|
49
|
+
export declare const fromFalsy: <T>(value: T | null | undefined | false | 0 | "") => Option<T>;
|
|
50
|
+
/** Applies `f` to a held value; `none` passes through as is. */
|
|
51
|
+
export declare const map: <T, U>(option: Option<T>, f: (value: T) => U) => Option<U>;
|
|
52
|
+
/**
|
|
53
|
+
* Applies `f`, which returns an option, to a held value; `none` passes through
|
|
54
|
+
* as is.
|
|
55
|
+
*/
|
|
56
|
+
export declare const flatMap: <T, U>(option: Option<T>, f: (value: T) => Option<U>) => Option<U>;
|
|
57
|
+
/** Keeps a held value that passes `predicate`, and returns `none` otherwise. */
|
|
58
|
+
export declare const filter: <T>(option: Option<T>, predicate: (value: T) => boolean) => Option<T>;
|
|
59
|
+
/**
|
|
60
|
+
* Returns the held value, or `fallback` for `none`. A function fallback is
|
|
61
|
+
* called only when it is needed.
|
|
62
|
+
*/
|
|
63
|
+
export declare const getOrElse: <T>(option: Option<T>, fallback: T | (() => T)) => T;
|
|
64
|
+
/** Returns the held value, or `null` for `none`. */
|
|
65
|
+
export declare const getOrNull: <T>(option: Option<T>) => T | null;
|
|
66
|
+
/** Returns the held value, or `undefined` for `none`. */
|
|
67
|
+
export declare const getOrUndefined: <T>(option: Option<T>) => T | undefined;
|
|
68
|
+
/** Returns the held value, or throws an `Error` with `message` for `none`. */
|
|
69
|
+
export declare const getOrThrow: <T>(option: Option<T>, message?: string) => T;
|
|
70
|
+
/** Calls `handlers.some` with the held value or `handlers.none`. */
|
|
71
|
+
export declare const match: <T, U>(option: Option<T>, handlers: {
|
|
72
|
+
some: (value: T) => U;
|
|
73
|
+
none: () => U;
|
|
74
|
+
}) => U;
|
|
75
|
+
/**
|
|
76
|
+
* Converts a held value to a success, and `none` to a failure that holds
|
|
77
|
+
* `error`. A function error is called only when it is needed.
|
|
78
|
+
*/
|
|
79
|
+
export declare const toResult: <T, E>(option: Option<T>, error: E | (() => E)) => results.Result<T, E>;
|
|
80
|
+
/** Converts a success to `some(value)`, and a failure to `none`. */
|
|
81
|
+
export declare const fromResult: <T, E>(result: results.Result<T, E>) => Option<T>;
|
|
82
|
+
/** Collects every held value in order, or returns `none` if any is `none`. */
|
|
83
|
+
export declare const all: <T>(options: ReadonlyArray<Option<T>>) => Option<T[]>;
|
|
84
|
+
/** Returns the first option that holds a value, or `none`. */
|
|
85
|
+
export declare const any: <T>(options: ReadonlyArray<Option<T>>) => Option<T>;
|
|
86
|
+
/**
|
|
87
|
+
* Returns `option` when it holds a value, and `alternative` otherwise. A
|
|
88
|
+
* function alternative is called only when it is needed.
|
|
89
|
+
*/
|
|
90
|
+
export declare const orElse: <T>(option: Option<T>, alternative: Option<T> | (() => Option<T>)) => Option<T>;
|
|
91
|
+
/** Calls `fn` with a held value and returns `option` unchanged. */
|
|
92
|
+
export declare const tap: <T>(option: Option<T>, fn: (value: T) => void) => Option<T>;
|
|
93
|
+
/** Calls `fn` when `option` is `none` and returns `option` unchanged. */
|
|
94
|
+
export declare const tapNone: <T>(option: Option<T>, fn: () => void) => Option<T>;
|
|
95
|
+
/** Pairs two held values, or returns `none` if either option is `none`. */
|
|
96
|
+
export declare const zip: <T, U>(optionA: Option<T>, optionB: Option<U>) => Option<[T, U]>;
|
|
97
|
+
/**
|
|
98
|
+
* Combines two held values with `f`, or returns `none` if either option is
|
|
99
|
+
* `none`.
|
|
100
|
+
*/
|
|
101
|
+
export declare const zipWith: <T, U, R>(optionA: Option<T>, optionB: Option<U>, f: (a: T, b: U) => R) => Option<R>;
|
|
102
|
+
/** Returns true when `option` holds a value strictly equal to `value`. */
|
|
103
|
+
export declare const contains: <T>(option: Option<T>, value: T) => boolean;
|
|
104
|
+
/** Returns true when `option` holds a value that passes `predicate`. */
|
|
105
|
+
export declare const exists: <T>(option: Option<T>, predicate: (value: T) => boolean) => boolean;
|
package/dist/options.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* The Option type: a value that is either present (`Some`) or absent (`None`),
|
|
4
|
+
* with its constructors, type guards and combinators.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import * as primitives from "@eserstack/primitives";
|
|
9
|
+
*
|
|
10
|
+
* const env: Record<string, string | undefined> = { PORT: "8080" };
|
|
11
|
+
* const port = primitives.options.fromNullable(env["PORT"]);
|
|
12
|
+
*
|
|
13
|
+
* const value = primitives.options.getOrElse(
|
|
14
|
+
* primitives.options.map(port, Number),
|
|
15
|
+
* 3000,
|
|
16
|
+
* );
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import * as results from "./results.js";
|
|
22
|
+
// Constructors
|
|
23
|
+
/** Wraps `value` in an option that holds it. */
|
|
24
|
+
export const some = (value) => ({ _tag: "Some", value });
|
|
25
|
+
/** The option that holds no value. */
|
|
26
|
+
export const none = { _tag: "None" };
|
|
27
|
+
// Type guards
|
|
28
|
+
/** Returns true when `option` holds a value, and narrows it to `Some<T>`. */
|
|
29
|
+
export const isSome = (option) => option._tag === "Some";
|
|
30
|
+
/** Returns true when `option` holds no value, and narrows it to `None`. */
|
|
31
|
+
export const isNone = (option) => option._tag === "None";
|
|
32
|
+
// From nullable values
|
|
33
|
+
/** Returns `none` for `null` or `undefined`, and `some(value)` otherwise. */
|
|
34
|
+
export const fromNullable = (value) => value === null || value === undefined ? none : some(value);
|
|
35
|
+
/**
|
|
36
|
+
* Returns `none` for a falsy value, such as `null`, `undefined`, `false`, `0`
|
|
37
|
+
* or `""`, and `some(value)` otherwise.
|
|
38
|
+
*/
|
|
39
|
+
export const fromFalsy = (value) => (value ? some(value) : none);
|
|
40
|
+
// Combinators
|
|
41
|
+
/** Applies `f` to a held value; `none` passes through as is. */
|
|
42
|
+
export const map = (option, f) => isSome(option) ? some(f(option.value)) : none;
|
|
43
|
+
/**
|
|
44
|
+
* Applies `f`, which returns an option, to a held value; `none` passes through
|
|
45
|
+
* as is.
|
|
46
|
+
*/
|
|
47
|
+
export const flatMap = (option, f) => (isSome(option) ? f(option.value) : none);
|
|
48
|
+
/** Keeps a held value that passes `predicate`, and returns `none` otherwise. */
|
|
49
|
+
export const filter = (option, predicate) => (isSome(option) && predicate(option.value) ? option : none);
|
|
50
|
+
// Value extraction
|
|
51
|
+
/**
|
|
52
|
+
* Returns the held value, or `fallback` for `none`. A function fallback is
|
|
53
|
+
* called only when it is needed.
|
|
54
|
+
*/
|
|
55
|
+
export const getOrElse = (option, fallback) => isSome(option)
|
|
56
|
+
? option.value
|
|
57
|
+
: typeof fallback === "function"
|
|
58
|
+
? fallback()
|
|
59
|
+
: fallback;
|
|
60
|
+
/** Returns the held value, or `null` for `none`. */
|
|
61
|
+
export const getOrNull = (option) => isSome(option) ? option.value : null;
|
|
62
|
+
/** Returns the held value, or `undefined` for `none`. */
|
|
63
|
+
export const getOrUndefined = (option) => isSome(option) ? option.value : undefined;
|
|
64
|
+
/** Returns the held value, or throws an `Error` with `message` for `none`. */
|
|
65
|
+
export const getOrThrow = (option, message = "Option is None") => {
|
|
66
|
+
if (isSome(option))
|
|
67
|
+
return option.value;
|
|
68
|
+
throw new Error(message);
|
|
69
|
+
};
|
|
70
|
+
// Pattern matching
|
|
71
|
+
/** Calls `handlers.some` with the held value or `handlers.none`. */
|
|
72
|
+
export const match = (option, handlers) => (isSome(option) ? handlers.some(option.value) : handlers.none());
|
|
73
|
+
// Conversion to Result
|
|
74
|
+
/**
|
|
75
|
+
* Converts a held value to a success, and `none` to a failure that holds
|
|
76
|
+
* `error`. A function error is called only when it is needed.
|
|
77
|
+
*/
|
|
78
|
+
export const toResult = (option, error) => isSome(option)
|
|
79
|
+
? results.ok(option.value)
|
|
80
|
+
: results.fail(typeof error === "function" ? error() : error);
|
|
81
|
+
// From Result
|
|
82
|
+
/** Converts a success to `some(value)`, and a failure to `none`. */
|
|
83
|
+
export const fromResult = (result) => result._tag === "Ok" ? some(result.value) : none;
|
|
84
|
+
// Collection utilities
|
|
85
|
+
/** Collects every held value in order, or returns `none` if any is `none`. */
|
|
86
|
+
export const all = (options) => {
|
|
87
|
+
const values = [];
|
|
88
|
+
for (const option of options) {
|
|
89
|
+
if (isNone(option))
|
|
90
|
+
return none;
|
|
91
|
+
values.push(option.value);
|
|
92
|
+
}
|
|
93
|
+
return some(values);
|
|
94
|
+
};
|
|
95
|
+
/** Returns the first option that holds a value, or `none`. */
|
|
96
|
+
export const any = (options) => {
|
|
97
|
+
for (const option of options) {
|
|
98
|
+
if (isSome(option))
|
|
99
|
+
return option;
|
|
100
|
+
}
|
|
101
|
+
return none;
|
|
102
|
+
};
|
|
103
|
+
// Alternative/fallback
|
|
104
|
+
/**
|
|
105
|
+
* Returns `option` when it holds a value, and `alternative` otherwise. A
|
|
106
|
+
* function alternative is called only when it is needed.
|
|
107
|
+
*/
|
|
108
|
+
export const orElse = (option, alternative) => isSome(option)
|
|
109
|
+
? option
|
|
110
|
+
: typeof alternative === "function"
|
|
111
|
+
? alternative()
|
|
112
|
+
: alternative;
|
|
113
|
+
// Tap utilities (for side effects)
|
|
114
|
+
/** Calls `fn` with a held value and returns `option` unchanged. */
|
|
115
|
+
export const tap = (option, fn) => {
|
|
116
|
+
if (isSome(option))
|
|
117
|
+
fn(option.value);
|
|
118
|
+
return option;
|
|
119
|
+
};
|
|
120
|
+
/** Calls `fn` when `option` is `none` and returns `option` unchanged. */
|
|
121
|
+
export const tapNone = (option, fn) => {
|
|
122
|
+
if (isNone(option))
|
|
123
|
+
fn();
|
|
124
|
+
return option;
|
|
125
|
+
};
|
|
126
|
+
// Zip/combine
|
|
127
|
+
/** Pairs two held values, or returns `none` if either option is `none`. */
|
|
128
|
+
export const zip = (optionA, optionB) => isSome(optionA) && isSome(optionB)
|
|
129
|
+
? some([optionA.value, optionB.value])
|
|
130
|
+
: none;
|
|
131
|
+
/**
|
|
132
|
+
* Combines two held values with `f`, or returns `none` if either option is
|
|
133
|
+
* `none`.
|
|
134
|
+
*/
|
|
135
|
+
export const zipWith = (optionA, optionB, f) => isSome(optionA) && isSome(optionB)
|
|
136
|
+
? some(f(optionA.value, optionB.value))
|
|
137
|
+
: none;
|
|
138
|
+
// Contains check
|
|
139
|
+
/** Returns true when `option` holds a value strictly equal to `value`. */
|
|
140
|
+
export const contains = (option, value) => isSome(option) && option.value === value;
|
|
141
|
+
/** Returns true when `option` holds a value that passes `predicate`. */
|
|
142
|
+
export const exists = (option, predicate) => isSome(option) && predicate(option.value);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for values that may arrive synchronously or asynchronously.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import * as primitives from "@eserstack/primitives";
|
|
7
|
+
*
|
|
8
|
+
* type MaybeAsync = primitives.promises.Promisable<string>;
|
|
9
|
+
*
|
|
10
|
+
* const load = (cached: string | null): MaybeAsync =>
|
|
11
|
+
* cached ?? Promise.resolve("fresh");
|
|
12
|
+
*
|
|
13
|
+
* const value = await load(null);
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
/** A value of type `T`, or a promise that resolves to one. */
|
|
19
|
+
export type Promisable<T> = Promise<T> | T;
|
|
20
|
+
/** A generator or an async generator that yields values of type `T`. */
|
|
21
|
+
export type Generatable<T> = AsyncGenerator<T> | Generator<T>;
|
package/dist/promises.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Result type: a value that is either a success (`Ok`) or a failure
|
|
3
|
+
* (`Fail`), with its constructors, type guards and combinators. Each result
|
|
4
|
+
* is iterable, so `yield*` inside a generator unwraps an `Ok` or stops the
|
|
5
|
+
* runner (such as `run` in @eserstack/functions) at the first `Fail`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as primitives from "@eserstack/primitives";
|
|
10
|
+
*
|
|
11
|
+
* type PortResult = primitives.results.Result<number, string>;
|
|
12
|
+
*
|
|
13
|
+
* const parsePort = (input: string): PortResult => {
|
|
14
|
+
* const port = Number(input);
|
|
15
|
+
*
|
|
16
|
+
* return Number.isInteger(port)
|
|
17
|
+
* ? primitives.results.ok(port)
|
|
18
|
+
* : primitives.results.fail(`not a port: ${input}`);
|
|
19
|
+
* };
|
|
20
|
+
*
|
|
21
|
+
* const label = primitives.results.match(parsePort("8080"), {
|
|
22
|
+
* ok: (port) => `port ${port}`,
|
|
23
|
+
* fail: (error) => error,
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @module
|
|
28
|
+
*/
|
|
29
|
+
/** Either a success that holds a `T` or a failure that holds an `E`. */
|
|
30
|
+
export type Result<T, E = Error> = Ok<T> | Fail<E>;
|
|
31
|
+
/** A successful result that holds a value. Build one with `ok()`. */
|
|
32
|
+
export interface Ok<T> {
|
|
33
|
+
/** The discriminant that marks a success; `isOk()` checks it. */
|
|
34
|
+
readonly _tag: "Ok";
|
|
35
|
+
/** The value the operation produced. */
|
|
36
|
+
readonly value: T;
|
|
37
|
+
/**
|
|
38
|
+
* Yields this result once and returns what the runner passes back to
|
|
39
|
+
* `next()`. Runners such as `run` in @eserstack/functions pass `value`, so
|
|
40
|
+
* `yield* result` evaluates to it.
|
|
41
|
+
*/
|
|
42
|
+
[Symbol.iterator](): Generator<Ok<T>, T, unknown>;
|
|
43
|
+
}
|
|
44
|
+
/** A failed result that holds an error. Build one with `fail()`. */
|
|
45
|
+
export interface Fail<E> {
|
|
46
|
+
/** The discriminant that marks a failure; `isFail()` checks it. */
|
|
47
|
+
readonly _tag: "Fail";
|
|
48
|
+
/** The error the operation failed with. */
|
|
49
|
+
readonly error: E;
|
|
50
|
+
/**
|
|
51
|
+
* Yields this result for the runner to handle. Runners such as `run` in
|
|
52
|
+
* @eserstack/functions stop there and return this failure, so the generator
|
|
53
|
+
* never resumes past `yield* result`.
|
|
54
|
+
*/
|
|
55
|
+
[Symbol.iterator](): Generator<Fail<E>, never, unknown>;
|
|
56
|
+
}
|
|
57
|
+
/** Wraps `value` in a successful result. */
|
|
58
|
+
export declare const ok: <T>(value: T) => Ok<T>;
|
|
59
|
+
/** Wraps `error` in a failed result. */
|
|
60
|
+
export declare const fail: <E>(error: E) => Fail<E>;
|
|
61
|
+
/** Returns true when `result` is a success, and narrows it to `Ok<T>`. */
|
|
62
|
+
export declare const isOk: <T, E>(result: Result<T, E>) => result is Ok<T>;
|
|
63
|
+
/** Returns true when `result` is a failure, and narrows it to `Fail<E>`. */
|
|
64
|
+
export declare const isFail: <T, E>(result: Result<T, E>) => result is Fail<E>;
|
|
65
|
+
/** Applies `f` to the value of a success; a failure passes through as is. */
|
|
66
|
+
export declare const map: <T, U, E>(result: Result<T, E>, f: (value: T) => U) => Result<U, E>;
|
|
67
|
+
/**
|
|
68
|
+
* Applies `f`, which returns a result, to the value of a success; a failure
|
|
69
|
+
* passes through unchanged.
|
|
70
|
+
*/
|
|
71
|
+
export declare const flatMap: <T, U, E>(result: Result<T, E>, f: (value: T) => Result<U, E>) => Result<U, E>;
|
|
72
|
+
/** `flatMap` with a widened error type: the error is `E1 | E2`. */
|
|
73
|
+
export declare const flatMapW: <T, U, E1, E2>(result: Result<T, E1>, f: (value: T) => Result<U, E2>) => Result<U, E1 | E2>;
|
|
74
|
+
/** Applies `f` to the error of a failure; a success passes through as is. */
|
|
75
|
+
export declare const mapError: <T, E, E2>(result: Result<T, E>, f: (error: E) => E2) => Result<T, E2>;
|
|
76
|
+
/**
|
|
77
|
+
* Applies `f`, which returns a result, to the error of a failure, so a failure
|
|
78
|
+
* can recover; a success passes through unchanged.
|
|
79
|
+
*/
|
|
80
|
+
export declare const flatMapError: <T, E, E2>(result: Result<T, E>, f: (error: E) => Result<T, E2>) => Result<T, E2>;
|
|
81
|
+
/** `flatMapError` with a widened error type: the error is `E1 | E2`. */
|
|
82
|
+
export declare const flatMapErrorW: <T, E1, E2>(result: Result<T, E1>, f: (error: E1) => Result<T, E2>) => Result<T, E1 | E2>;
|
|
83
|
+
/**
|
|
84
|
+
* Returns the value of a success, or `fallback` for a failure. A function
|
|
85
|
+
* fallback is called with the error.
|
|
86
|
+
*/
|
|
87
|
+
export declare const getOrElse: <T, E>(result: Result<T, E>, fallback: T | ((error: E) => T)) => T;
|
|
88
|
+
/**
|
|
89
|
+
* Returns the value of a success, or throws the error of a failure. An error
|
|
90
|
+
* that is not an `Error` is wrapped in one.
|
|
91
|
+
*/
|
|
92
|
+
export declare const getOrThrow: <T, E>(result: Result<T, E>) => T;
|
|
93
|
+
/** Returns the value of a success, or `null` for a failure. */
|
|
94
|
+
export declare const getOrNull: <T, E>(result: Result<T, E>) => T | null;
|
|
95
|
+
/** Returns the value of a success, or `undefined` for a failure. */
|
|
96
|
+
export declare const getOrUndefined: <T, E>(result: Result<T, E>) => T | undefined;
|
|
97
|
+
/** Calls `handlers.ok` with the value or `handlers.fail` with the error. */
|
|
98
|
+
export declare const match: <T, E, U>(result: Result<T, E>, handlers: {
|
|
99
|
+
ok: (value: T) => U;
|
|
100
|
+
fail: (error: E) => U;
|
|
101
|
+
}) => U;
|
|
102
|
+
/**
|
|
103
|
+
* Awaits `promise` and returns its value as a success, or the rejection as a
|
|
104
|
+
* failure, mapped through `onError`.
|
|
105
|
+
*/
|
|
106
|
+
export declare const fromPromise: <T, E = Error>(promise: Promise<T>, onError?: (error: unknown) => E) => Promise<Result<T, E>>;
|
|
107
|
+
/**
|
|
108
|
+
* Resolves with the value of a success, or rejects with the error of a
|
|
109
|
+
* failure. An error that is not an `Error` is wrapped in one.
|
|
110
|
+
*/
|
|
111
|
+
export declare const toPromise: <T, E>(result: Result<T, E>) => Promise<T>;
|
|
112
|
+
/**
|
|
113
|
+
* Collects the values of all successes in order, or returns the first failure.
|
|
114
|
+
*/
|
|
115
|
+
export declare const all: <T, E>(items: ReadonlyArray<Result<T, E>>) => Result<T[], E>;
|
|
116
|
+
/** Returns the first success, or a failure that holds every error in order. */
|
|
117
|
+
export declare const any: <T, E>(items: ReadonlyArray<Result<T, E>>) => Result<T, E[]>;
|
|
118
|
+
/**
|
|
119
|
+
* Calls `fn` and returns its value as a success, or the thrown error as a
|
|
120
|
+
* failure, mapped through `onError`.
|
|
121
|
+
*/
|
|
122
|
+
export declare const tryCatch: <T, E = Error>(fn: () => T, onError?: (error: unknown) => E) => Result<T, E>;
|
|
123
|
+
/**
|
|
124
|
+
* Awaits `fn()` and returns its value as a success, or the thrown or rejected
|
|
125
|
+
* error as a failure, mapped through `onError`.
|
|
126
|
+
*/
|
|
127
|
+
export declare const tryCatchAsync: <T, E = Error>(fn: () => Promise<T>, onError?: (error: unknown) => E) => Promise<Result<T, E>>;
|
|
128
|
+
/** Calls `fn` with the value of a success and returns `result` unchanged. */
|
|
129
|
+
export declare const tap: <T, E>(result: Result<T, E>, fn: (value: T) => void) => Result<T, E>;
|
|
130
|
+
/** Calls `fn` with the error of a failure and returns `result` unchanged. */
|
|
131
|
+
export declare const tapError: <T, E>(result: Result<T, E>, fn: (error: E) => void) => Result<T, E>;
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
// Constructors with iterator support for do-notation
|
|
3
|
+
/** Wraps `value` in a successful result. */
|
|
4
|
+
export const ok = (value) => ({
|
|
5
|
+
_tag: "Ok",
|
|
6
|
+
value,
|
|
7
|
+
*[Symbol.iterator]() {
|
|
8
|
+
return (yield this);
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
/** Wraps `error` in a failed result. */
|
|
12
|
+
export const fail = (error) => ({
|
|
13
|
+
_tag: "Fail",
|
|
14
|
+
error,
|
|
15
|
+
*[Symbol.iterator]() {
|
|
16
|
+
return (yield this);
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
// Type guards
|
|
20
|
+
/** Returns true when `result` is a success, and narrows it to `Ok<T>`. */
|
|
21
|
+
export const isOk = (result) => result._tag === "Ok";
|
|
22
|
+
/** Returns true when `result` is a failure, and narrows it to `Fail<E>`. */
|
|
23
|
+
export const isFail = (result) => result._tag === "Fail";
|
|
24
|
+
// Combinators
|
|
25
|
+
/** Applies `f` to the value of a success; a failure passes through as is. */
|
|
26
|
+
export const map = (result, f) => (isOk(result) ? ok(f(result.value)) : result);
|
|
27
|
+
/**
|
|
28
|
+
* Applies `f`, which returns a result, to the value of a success; a failure
|
|
29
|
+
* passes through unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export const flatMap = (result, f) => (isOk(result) ? f(result.value) : result);
|
|
32
|
+
/** `flatMap` with a widened error type: the error is `E1 | E2`. */
|
|
33
|
+
export const flatMapW = (result, f) => (isOk(result) ? f(result.value) : result);
|
|
34
|
+
/** Applies `f` to the error of a failure; a success passes through as is. */
|
|
35
|
+
export const mapError = (result, f) => (isFail(result) ? fail(f(result.error)) : result);
|
|
36
|
+
/**
|
|
37
|
+
* Applies `f`, which returns a result, to the error of a failure, so a failure
|
|
38
|
+
* can recover; a success passes through unchanged.
|
|
39
|
+
*/
|
|
40
|
+
export const flatMapError = (result, f) => (isFail(result) ? f(result.error) : result);
|
|
41
|
+
/** `flatMapError` with a widened error type: the error is `E1 | E2`. */
|
|
42
|
+
export const flatMapErrorW = (result, f) => (isFail(result) ? f(result.error) : result);
|
|
43
|
+
// Value extraction
|
|
44
|
+
/**
|
|
45
|
+
* Returns the value of a success, or `fallback` for a failure. A function
|
|
46
|
+
* fallback is called with the error.
|
|
47
|
+
*/
|
|
48
|
+
export const getOrElse = (result, fallback) => isOk(result)
|
|
49
|
+
? result.value
|
|
50
|
+
: typeof fallback === "function"
|
|
51
|
+
? fallback(result.error)
|
|
52
|
+
: fallback;
|
|
53
|
+
/**
|
|
54
|
+
* Returns the value of a success, or throws the error of a failure. An error
|
|
55
|
+
* that is not an `Error` is wrapped in one.
|
|
56
|
+
*/
|
|
57
|
+
export const getOrThrow = (result) => {
|
|
58
|
+
if (isOk(result))
|
|
59
|
+
return result.value;
|
|
60
|
+
throw result.error instanceof Error
|
|
61
|
+
? result.error
|
|
62
|
+
: new Error(String(result.error));
|
|
63
|
+
};
|
|
64
|
+
/** Returns the value of a success, or `null` for a failure. */
|
|
65
|
+
export const getOrNull = (result) => isOk(result) ? result.value : null;
|
|
66
|
+
/** Returns the value of a success, or `undefined` for a failure. */
|
|
67
|
+
export const getOrUndefined = (result) => isOk(result) ? result.value : undefined;
|
|
68
|
+
// Pattern matching
|
|
69
|
+
/** Calls `handlers.ok` with the value or `handlers.fail` with the error. */
|
|
70
|
+
export const match = (result, handlers) => isOk(result) ? handlers.ok(result.value) : handlers.fail(result.error);
|
|
71
|
+
// Async utilities
|
|
72
|
+
/**
|
|
73
|
+
* Awaits `promise` and returns its value as a success, or the rejection as a
|
|
74
|
+
* failure, mapped through `onError`.
|
|
75
|
+
*/
|
|
76
|
+
export const fromPromise = async (promise, onError = (e) => e) => {
|
|
77
|
+
try {
|
|
78
|
+
return ok(await promise);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
return fail(onError(error));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Resolves with the value of a success, or rejects with the error of a
|
|
86
|
+
* failure. An error that is not an `Error` is wrapped in one.
|
|
87
|
+
*/
|
|
88
|
+
export const toPromise = (result) => isOk(result)
|
|
89
|
+
? Promise.resolve(result.value)
|
|
90
|
+
: Promise.reject(result.error instanceof Error
|
|
91
|
+
? result.error
|
|
92
|
+
: new Error(String(result.error)));
|
|
93
|
+
// Collection utilities
|
|
94
|
+
/**
|
|
95
|
+
* Collects the values of all successes in order, or returns the first failure.
|
|
96
|
+
*/
|
|
97
|
+
export const all = (items) => {
|
|
98
|
+
const values = [];
|
|
99
|
+
for (const result of items) {
|
|
100
|
+
if (isFail(result))
|
|
101
|
+
return result;
|
|
102
|
+
values.push(result.value);
|
|
103
|
+
}
|
|
104
|
+
return ok(values);
|
|
105
|
+
};
|
|
106
|
+
/** Returns the first success, or a failure that holds every error in order. */
|
|
107
|
+
export const any = (items) => {
|
|
108
|
+
const errors = [];
|
|
109
|
+
for (const result of items) {
|
|
110
|
+
if (isOk(result))
|
|
111
|
+
return result;
|
|
112
|
+
errors.push(result.error);
|
|
113
|
+
}
|
|
114
|
+
return fail(errors);
|
|
115
|
+
};
|
|
116
|
+
// Try/catch wrappers
|
|
117
|
+
/**
|
|
118
|
+
* Calls `fn` and returns its value as a success, or the thrown error as a
|
|
119
|
+
* failure, mapped through `onError`.
|
|
120
|
+
*/
|
|
121
|
+
export const tryCatch = (fn, onError = (e) => e) => {
|
|
122
|
+
try {
|
|
123
|
+
return ok(fn());
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
return fail(onError(error));
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Awaits `fn()` and returns its value as a success, or the thrown or rejected
|
|
131
|
+
* error as a failure, mapped through `onError`.
|
|
132
|
+
*/
|
|
133
|
+
export const tryCatchAsync = async (fn, onError = (e) => e) => {
|
|
134
|
+
try {
|
|
135
|
+
return ok(await fn());
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
return fail(onError(error));
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
// Tap utilities (for side effects)
|
|
142
|
+
/** Calls `fn` with the value of a success and returns `result` unchanged. */
|
|
143
|
+
export const tap = (result, fn) => {
|
|
144
|
+
if (isOk(result))
|
|
145
|
+
fn(result.value);
|
|
146
|
+
return result;
|
|
147
|
+
};
|
|
148
|
+
/** Calls `fn` with the error of a failure and returns `result` unchanged. */
|
|
149
|
+
export const tapError = (result, fn) => {
|
|
150
|
+
if (isFail(result))
|
|
151
|
+
fn(result.error);
|
|
152
|
+
return result;
|
|
153
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type guard utilities using .constructor checks per javascript-practices rules.
|
|
3
|
+
* Avoids typeof operator for type checking.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import * as primitives from "@eserstack/primitives";
|
|
8
|
+
*
|
|
9
|
+
* const value: unknown = JSON.parse('"hello"');
|
|
10
|
+
* const data: unknown = JSON.parse('{"name":"app"}');
|
|
11
|
+
*
|
|
12
|
+
* if (primitives.typeGuards.isString(value)) {
|
|
13
|
+
* console.log(value.toUpperCase());
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* if (primitives.typeGuards.isPlainObject(data)) {
|
|
17
|
+
* console.log(Object.keys(data));
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Checks if a value is a string primitive.
|
|
25
|
+
*/
|
|
26
|
+
export declare const isString: (value: unknown) => value is string;
|
|
27
|
+
/**
|
|
28
|
+
* Checks if a value is a number primitive (excluding NaN).
|
|
29
|
+
*/
|
|
30
|
+
export declare const isNumber: (value: unknown) => value is number;
|
|
31
|
+
/**
|
|
32
|
+
* Checks if a value is a boolean primitive.
|
|
33
|
+
*/
|
|
34
|
+
export declare const isBoolean: (value: unknown) => value is boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Checks if a value is an array.
|
|
37
|
+
*/
|
|
38
|
+
export declare const isArray: <T = unknown>(value: unknown) => value is T[];
|
|
39
|
+
/**
|
|
40
|
+
* Checks if a value is a plain object (not null, not array, constructor is Object).
|
|
41
|
+
*/
|
|
42
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
43
|
+
/**
|
|
44
|
+
* Checks if a value is defined (not null and not undefined).
|
|
45
|
+
*/
|
|
46
|
+
export declare const isDefined: <T>(value: T | null | undefined) => value is T;
|
|
47
|
+
/**
|
|
48
|
+
* Checks if a value is null or undefined.
|
|
49
|
+
*/
|
|
50
|
+
export declare const isNullish: (value: unknown) => value is null | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Checks if a value is a function.
|
|
53
|
+
*/
|
|
54
|
+
export declare const isFunction: (value: unknown) => value is (...args: unknown[]) => unknown;
|
|
55
|
+
/**
|
|
56
|
+
* Checks if a value is a Date instance.
|
|
57
|
+
*/
|
|
58
|
+
export declare const isDate: (value: unknown) => value is Date;
|
|
59
|
+
/**
|
|
60
|
+
* Checks if a value is a RegExp instance.
|
|
61
|
+
*/
|
|
62
|
+
export declare const isRegExp: (value: unknown) => value is RegExp;
|
|
63
|
+
/**
|
|
64
|
+
* Checks if a value is a Promise instance.
|
|
65
|
+
*/
|
|
66
|
+
export declare const isPromise: <T = unknown>(value: unknown) => value is Promise<T>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Type guard utilities using .constructor checks per javascript-practices rules.
|
|
4
|
+
* Avoids typeof operator for type checking.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import * as primitives from "@eserstack/primitives";
|
|
9
|
+
*
|
|
10
|
+
* const value: unknown = JSON.parse('"hello"');
|
|
11
|
+
* const data: unknown = JSON.parse('{"name":"app"}');
|
|
12
|
+
*
|
|
13
|
+
* if (primitives.typeGuards.isString(value)) {
|
|
14
|
+
* console.log(value.toUpperCase());
|
|
15
|
+
* }
|
|
16
|
+
*
|
|
17
|
+
* if (primitives.typeGuards.isPlainObject(data)) {
|
|
18
|
+
* console.log(Object.keys(data));
|
|
19
|
+
* }
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* @module
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Checks if a value is a string primitive.
|
|
26
|
+
*/
|
|
27
|
+
export const isString = (value) => value !== null &&
|
|
28
|
+
value !== undefined &&
|
|
29
|
+
value.constructor === String;
|
|
30
|
+
/**
|
|
31
|
+
* Checks if a value is a number primitive (excluding NaN).
|
|
32
|
+
*/
|
|
33
|
+
export const isNumber = (value) => value !== null &&
|
|
34
|
+
value !== undefined &&
|
|
35
|
+
value.constructor === Number &&
|
|
36
|
+
!Number.isNaN(value);
|
|
37
|
+
/**
|
|
38
|
+
* Checks if a value is a boolean primitive.
|
|
39
|
+
*/
|
|
40
|
+
export const isBoolean = (value) => value !== null &&
|
|
41
|
+
value !== undefined &&
|
|
42
|
+
value.constructor === Boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Checks if a value is an array.
|
|
45
|
+
*/
|
|
46
|
+
export const isArray = (value) => Array.isArray(value);
|
|
47
|
+
/**
|
|
48
|
+
* Checks if a value is a plain object (not null, not array, constructor is Object).
|
|
49
|
+
*/
|
|
50
|
+
export const isPlainObject = (value) => value !== null &&
|
|
51
|
+
value !== undefined &&
|
|
52
|
+
value.constructor === Object;
|
|
53
|
+
/**
|
|
54
|
+
* Checks if a value is defined (not null and not undefined).
|
|
55
|
+
*/
|
|
56
|
+
export const isDefined = (value) => value !== null && value !== undefined;
|
|
57
|
+
/**
|
|
58
|
+
* Checks if a value is null or undefined.
|
|
59
|
+
*/
|
|
60
|
+
export const isNullish = (value) => value === null || value === undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Checks if a value is a function.
|
|
63
|
+
*/
|
|
64
|
+
export const isFunction = (value) => value !== null &&
|
|
65
|
+
value !== undefined &&
|
|
66
|
+
value.constructor === Function;
|
|
67
|
+
/**
|
|
68
|
+
* Checks if a value is a Date instance.
|
|
69
|
+
*/
|
|
70
|
+
export const isDate = (value) => value instanceof Date;
|
|
71
|
+
/**
|
|
72
|
+
* Checks if a value is a RegExp instance.
|
|
73
|
+
*/
|
|
74
|
+
export const isRegExp = (value) => value instanceof RegExp;
|
|
75
|
+
/**
|
|
76
|
+
* Checks if a value is a Promise instance.
|
|
77
|
+
*/
|
|
78
|
+
export const isPromise = (value) => value instanceof Promise;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type-level helpers that slice tuple types, such as the parameter list of a
|
|
3
|
+
* partially applied function.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import type * as primitives from "@eserstack/primitives";
|
|
8
|
+
*
|
|
9
|
+
* type Params = [string, number, boolean];
|
|
10
|
+
*
|
|
11
|
+
* // string
|
|
12
|
+
* type Head = primitives.typeSlices.First<Params>;
|
|
13
|
+
* // [number, boolean]
|
|
14
|
+
* type Rest = primitives.typeSlices.RemainingParameters<Params, [string]>;
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
/** The type of the first element of the tuple `T`. */
|
|
20
|
+
export type First<T extends ReadonlyArray<any>> = T[0];
|
|
21
|
+
/** The type of the last element of the tuple `T`; `never` when it is empty. */
|
|
22
|
+
export type Last<T extends ReadonlyArray<any>> = T extends [
|
|
23
|
+
...infer _Rest,
|
|
24
|
+
infer Last
|
|
25
|
+
] ? Last : never;
|
|
26
|
+
/**
|
|
27
|
+
* The elements of `T1` that remain after removing as many leading elements as
|
|
28
|
+
* `T2` has: the parameters left once `T2` is applied from the left.
|
|
29
|
+
*/
|
|
30
|
+
export type RemainingParameters<T1 extends any[], T2 extends any[]> = T2 extends [any, ...infer T2Tail] ? T1 extends [any, ...infer T1Tail] ? RemainingParameters<T1Tail, T2Tail> : [] : T1;
|
|
31
|
+
/**
|
|
32
|
+
* The elements of `T1` that remain after removing as many trailing elements as
|
|
33
|
+
* `T2` has: the parameters left once `T2` is applied from the right.
|
|
34
|
+
*/
|
|
35
|
+
export type RemainingParametersRight<T1 extends any[], T2 extends any[]> = T2 extends [any, ...infer T2Tail] ? T1 extends [...infer T1Tail, any] ? RemainingParametersRight<T1Tail, T2Tail> : [] : T1;
|
package/package.json
CHANGED
|
@@ -1 +1,51 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@eserstack/primitives",
|
|
3
|
+
"version": "5.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/eser/stack",
|
|
8
|
+
"directory": "pkg/@eserstack/primitives"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/**/*.js",
|
|
12
|
+
"dist/**/*.d.ts",
|
|
13
|
+
"dist/**/*.json"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/mod.d.ts",
|
|
18
|
+
"import": "./dist/mod.js"
|
|
19
|
+
},
|
|
20
|
+
"./functions": {
|
|
21
|
+
"types": "./dist/functions.d.ts",
|
|
22
|
+
"import": "./dist/functions.js"
|
|
23
|
+
},
|
|
24
|
+
"./options": {
|
|
25
|
+
"types": "./dist/options.d.ts",
|
|
26
|
+
"import": "./dist/options.js"
|
|
27
|
+
},
|
|
28
|
+
"./promises": {
|
|
29
|
+
"types": "./dist/promises.d.ts",
|
|
30
|
+
"import": "./dist/promises.js"
|
|
31
|
+
},
|
|
32
|
+
"./results": {
|
|
33
|
+
"types": "./dist/results.d.ts",
|
|
34
|
+
"import": "./dist/results.js"
|
|
35
|
+
},
|
|
36
|
+
"./type-guards": {
|
|
37
|
+
"types": "./dist/type-guards.d.ts",
|
|
38
|
+
"import": "./dist/type-guards.js"
|
|
39
|
+
},
|
|
40
|
+
"./type-slices": {
|
|
41
|
+
"types": "./dist/type-slices.d.ts",
|
|
42
|
+
"import": "./dist/type-slices.js"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@eserstack/test-kit": "5.0.0"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "node ../../../etc/scripts/build-library.ts"
|
|
50
|
+
}
|
|
51
|
+
}
|