Either
The Either
data type encapsulates the idea of a computation that may fail.
An Either
value can either be Right
some value or Left
some error.
;
Install
npm install ts.data.either --save
Example
; // throws if file does not exists; // Wraps the read file operation in an Either; // Wraps the json parsing operation in an Either; // The pipeline function just makes function invocations flow; ; // returns the Array of users because all intermediate operations have succeeded ; // returns an empty Array because the readFile operations failed
Api
(Inspired by elm-lang)
right
right<T>(value: T): Either<T>
Wraps a value in an instance of Right
.
right5; // Right<number>(5)
left
left<T>(error: Error): Either<T>
Creates an instance of Left
.
leftnew Error'Something bad happened'; // Left<unknown>(Error('Something bad happened'))leftnew Error'The calculation failed'; // Left<number>(Error('The calculation failed'))
isRight
isRight<T>(value: Either<T>): boolean
Returns true if a value is an instance of Right
.
isRightleftnew Error'Wrong!'; // false
isLeft
isLeft<T>(value: Either<T>): boolean
Returns true if a value is not an instance of Right
.
isLeftright5; // falseisLeftleft'Hi!'; // trueisLeftnull; // true
withDefault
withDefault<T>(value: Either<T>, defaultValue: T): T
If value
is an instance of Right
it returns its wrapped value, if it's an instance of Left
it returns the defaultValue
.
withDefaultright5, 0; // 5withDefaultleftnew Error'Wrong!', 0; // 0
caseOf
caseOf<A, B>(caseof: {Right: (v: A) => B; Left: (err: Error) => B;}, value: Either<A>): B
Run different computations depending on whether an Either
is Right
or Left
and returns the result.
caseOf , right'5'; // 'Launch 5 missiles'
map
map<A, B>(f: (a: A) => B, value: Either<A>): Either<B>
Transforms an Either
value with a given function.
;mapadd1, right4; // Right<number>(5)mapadd1, leftnew Error'Something bad happened'; // Left('Something bad happened')
tryCatch
tryCatch<A>(f: () => A, onError: (e: Error) => Error): Either<A>
Transforms a function (that might throw an exception) that produces A
to a function that produces Either<A>
.
tryCatchJSON.parse'', err; // Left('Unexpected end of JSON input')
andThen
andThen<A, B>(f: (a: A) => Either<B>, value: Either<A>): Either<B>
Chains together computations that may fail.
; ; // The pipeline function just makes function invocations flow; ; console.logresult; // []