https://github.com/blackglory/return-style
🌲 Convert the result of any function or promise to the user's desired style.
https://github.com/blackglory/return-style
browser esm library nodejs npm-package typescript
Last synced: 2 months ago
JSON representation
🌲 Convert the result of any function or promise to the user's desired style.
- Host: GitHub
- URL: https://github.com/blackglory/return-style
- Owner: BlackGlory
- License: mit
- Created: 2019-09-28T08:06:45.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-06-11T06:20:36.000Z (about 3 years ago)
- Last Synced: 2025-05-25T18:54:56.783Z (about 1 year ago)
- Topics: browser, esm, library, nodejs, npm-package, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/return-style
- Size: 1.62 MB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# return-style
Non-intrusively convert the result of any function or promise to the user's desired style.
## Install
```sh
npm install --save return-style
# or
yarn add return-style
```
## API
All functions whose names are suffixed with `Async` can handle synchronous errors.
If you only need to catch asynchronous errors, use functions with the suffix `Promise`.
### isSuccess
```ts
function isSuccess(fn: () => unknown): boolean
function isSuccessAsync(fn: () => Awaitable): Promise
function isSuccessPromise(promise: PromiseLike): Promise
```
Return true when returning, false when throwing.
```ts
if (isSuccess(() => fn())) {
...
}
if (await isSuccessAsync(() => asyncFn())) {
...
}
if (await isSuccessPromise(promise)) {
...
}
```
### isFailure
```ts
function isFailure(fn: () => unknown): boolean
function isFailureAsync(fn: () => Awaitable): Promise
function isFailurePromise(promise: PromiseLike): Promise
```
Return true when throwing, true when returning.
```ts
if (isFailure(() => fn())) {
...
}
if (await isFailureAsync(() => asyncFn())) {
...
}
if (await isFailurePromise(promise)) {
...
}
```
### getResult
```ts
function getResult(fn: () => T): T | undefined
function getResultAsync(fn: () => Awaitable): Promise
function getResultPromise(promise: PromiseLike): Promise
```
```js
const result = getResult(() => fn())
if (result) {
...
}
const result = await getResultAsync(() => asyncFn())
if (result) {
...
}
const result = await getResultPromise(promise)
if (result) {
...
}
```
### getError
```ts
function getError(fn: () => unknown): E | undefined
function getErrorAsync(fn: () => Awaitable): Promise
function getErrorPromise(promise: PromiseLike): Promise
function getErrorAsyncIterable(iterable: AsyncIterable): Promise
```
Designed for testing, helping to achieve Arrange-Act-Assert pattern.
```js
// BAD: try...catch
test('divided by zero', () => {
expect.hasAssertions()
const calc = createCalculator()
try {
calc.eval('1 / 0')
} catch (err) {
expect(err).toInstanceOf(Error)
}
})
// BAD: toThrow
test('divided by zero', () => {
const calc = createCalculator()
expect(() => calc.eval('1 / 0')).toThrow(Error)
})
// GOOD: Arrange, Act, Assert
test('divided by zero', () => {
const calc = createCalculator()
const err = getError(() => calc.eval('1 / 0'))
expect(err).toInstanceOf(Error)
})
```
### Tuple / Go-like
Since modern JavaScript does not advocate repeated declarations of variables (`var`), this style can sometimes be difficult to use.
#### [Error, Result]
```ts
function getErrorResult(fn: () => T): [undefined, T] | [E, undefined]
function getErrorResultAsync(fn: () => Awaitable): Promise<[undefined, T] | [E, undefined]>
function getErrorResultPromise(promise: PromiseLike): Promise<[undefined, T] | [E, undefined]>
```
Return tuple (Error, Result).
```ts
const [err, ret] = getErrorResult(() => fn())
const [err] = getErrorResult(() => fn())
const [err, ret] = await getErrorResultAsync(() => fnAsync())
const [err] = await getErrorResultAsync(() => fnAsync())
const [err, ret] = await getErrorResultAsync(promise)
const [err] = await getErrorResultAsync(promise)
```
#### [Result, Error]
```ts
function getResultError(fn: () => T): [T, undefined] | [undefined, E]
function getResultErrorAsync(fn: () => Awaitable): Promise<[T, undefined] | [undefined, E]>
function getResultErrorPromise(promise: PromiseLike): Promise<[T, undefined] | [undefined, E]>
```
Return tuple (Result, Error).
```ts
const [ret, err] = getResultError(() => fn())
const [ret] = getResultError(() => fn())
const [ret, err] = await getResultErrorAsync(() => fn())
const [ret] = await getResultErrorAsync(() => fn())
const [ret, err] = await getResultErrorPromise(promise)
const [ret] = await getResultErrorPromise(promise)
```
#### [isSuccess, Result | undefined]
```ts
function getSuccess(fn: () => T): [true, T] | [false, undefined]
function getSuccessAsync(fn: () => Awaitable): Promise<[true, T] | [false, undefined]>
function getSuccessPromise(promise: PromiseLike): Promise<[true, T] | [false, undefined]>
```
Return tuple (isSuccess, Result | undefined)
```ts
const [succ, ret] = getSuccess(() => fn())
const [succ, ret] = await getSuccessAsync(() => asyncFn())
const [succ, ret] = await getSuccessPromise(promise)
```
#### [isFailure, Error | undefined]
```ts
function getFailure(fn: () => unknown): [true, E] | [false, undefined]
function getFailureAsync(fn: () => Awaitable): Promise<[true, E] | [false, undefined]>
function getFailurePromise(promise: PromiseLike): Promise<[true, E] | [false, undefined]>
```
Return tuple (isFailure, Error | undefined)
```ts
const [fail, ret] = getFailure(() => fn())
const [fail, ret] = await getFailureAsync(() => asyncFn())
const [fail, ret] = await getFailurePromise(promise)
```
### ADT / Rust-like / Haskell-like
#### Result = Ok | Err
```ts
function toResult(fn: () => T): Result
function toResultAsync(fn: () => Awaitable): Promise>
function toResultPromise(promise: PromiseLike): Promise>
```
`Result` is designed according to Rust's enumeration of the same name,
please refer to the relevant documentation.
```ts
class Result {
static Ok(val: T) => Result
static Err(err: E) => Result
isOk(): boolean
isErr(): boolean
map(mapper: (val: T) => U): Result
mapOr(defaultValue: U, mapper: (val: T) => U): Result
mapOrElse(createDefaultValue: (err: E) => U, mapper: (val: T) => U): Result
mapErr(mapper: (err: E) => U): Result
/**
* @throws {E}
*/
unwrap(): T
unwrapOr(defaultValue: U): T | U
unwrapOrElse(createDefaultValue: (err: E) => U): T | U
/**
* @throws {Error}
*/
unwrapErr(): E
/**
* @throws {Error}
*/
expect(message: string): T
/**
* @throws {Error}
*/
expectErr(message: string): E
ok(): Option
err(): Option
}
```
#### Option = Some | None
```ts
function toOption(fn: () => T): Option
function toOptionAsync(fn: () => Awaitable): Promise>
function toOptionPromise(promise: PromiseLike): Promise>
```
`Option` is designed according to Rust's enumeration of the same name,
please refer to the relevant documentation.
```ts
class Option {
static Some(val: T) => Option
static None() => Option
isSome(): boolean
isNone(): boolean
map(mapper: (val: T) => U): Option
mapOr(defaultValue: U, mapper: (val: T) => U): Option
mapOrElse(createDefaultValue: () => U, mapper: (val: T) => U): Option
filter(predicate: (val: T) => boolean): Option
/**
* @throws {Error}
*/
unwrap(): T
unwrapOr(defaultValue: U): T | U
unwrapOrElse(createDefaultValue: () => U): T | U
/**
* @throws {Error}
*/
expect(message: string): T
okOr(err: E): Result
okOrElse(createErr: () => E): Result
}
```