Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pedromsilvapt/data-either
Simple TypeScript/ES2017 class to represent either values
https://github.com/pedromsilvapt/data-either
Last synced: 11 days ago
JSON representation
Simple TypeScript/ES2017 class to represent either values
- Host: GitHub
- URL: https://github.com/pedromsilvapt/data-either
- Owner: pedromsilvapt
- Created: 2018-01-31T11:59:27.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2018-04-25T12:32:59.000Z (over 6 years ago)
- Last Synced: 2024-10-06T15:18:12.005Z (3 months ago)
- Language: TypeScript
- Size: 4.88 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Either
> Simple TypeScript/ES2017 class to represent either values
# Installation
```shell
npm install --save data-either
```# Usage
```typescript
import { Either } from 'data-either';const left = Either.left( 1 );
const right = Either.right( 20 );left.isRight(); // false
right.isRight(); // true
```You can also convert trowable functions into either.
```typescript
import { Either } from 'data-either';const left = Either.ofThrowable( () => 2 );
const right = Either.ofThrowable( () => { throw new Error(); } );left.getLeft(); // 2
right.getRight(); // Error
```Convert a Promise that can reject into an always resolved promise.
```typescript
import { Either } from 'data-either';const left = Either.ofPromise( Promise.resolve( "left" ) );
const right = Either.ofPromise( Promise.reject( new Error() ) );left.getLeft(); // "left"
right.getRight(); // Error
```There are also a number of computations that can be done functionally with this module.
```typescript
import { Either } from 'data-either';let value : Either = Either.left( 1 );
value = value.map( n => n * 3, err => `Error: ${ err }` ); // Either.left( 3 )
value = value.flatMap( n => n % 2 === 0 ? Either.left( n ) : Either.right( "Error: Not event." ), r => Either.right( r ) ); // Either.right( "Error: Not even." )
// Or simply
value = value.flatMapLeft( n => n % 2 === 0 ? Either.left( n ) : Either.right( "Error: Not event." ) ); // Either.right( "Error: Not even." )value.leftOrElse( 0 ); // 0
```