Either implementation for union-type. See also union-type-option.
- Setoid
- Foldable
- Functor
- Apply
- Chain
- Applicative
- Monad
- Extract
Like Ramda, the functions in this lib take
the Either
instance as the final argument. All functions with more than one
argument are auto-curried using ramda.
This library is written in node-supported es2015 (4.0+) so if you're running in an old environment you may need to transpile to es5.
var Either = require('union-type-either')
var Right = Either.Right
var Left = Either.Left
Create an instance of Either
with a valid value.
Right(1) // Right(1)
Create an instance of Either
with a default value.
Left('Danger Will Robinson')
Compare the contained value of one Either
against another using ===
.
Either.equals(Right(1), Right(1)) //true
Either.equals(Right({}), Right({})) //false
Either.equals(Left('Doh'), Left('Doh')) //true
Run a function on a value in an Either
and return new Either with the result.
Either.map(a => a + 3, Right(1)) // Right(4)
Get the value out of an Either
. Could be Left
or Right
.
Either.extract(Right(1)) // 1
Either.extract(Left('Doh')) // 'Doh'
Put a value in an Either
. Mostly useful for higher level operations.
Either.of(1, Left('Doh')) // Right(1)
Either.of(1, Right(999)) // Right(1)
Run a function that returns an Either
on the value in another Either
.
var validLength = str => str.length < 8 ? Left('Passwords must contain at least 8 characters') : Right(str)
var validHasCapitals = str => (/[A-Z]/).test(str) ? Right(str) : Left('Password must contain at least one capital')
var validateUsername = username => Either.chain(validHasCapitals, validLength(username))
Like chain but only applies to Left
values.
Like chain but takes two functions and applies one of them to Left or Right.
Run a function inside an Either
on the value in another Either
Either.ap(Right(2), Right(a => a * 2)) // Right(4)
Turn an option into something else by combining its right value with a seed and a reducing function.
Either.reduce((a, b) => a + b, 1, Right(2)) // Right(3)
Run a function on an Either
and wrap with another Either
.
Either.extend(a => a.extract() + 1, Right(1)) // 2
Catamorphism. Run a function on the value of both branches of an Either
Either.cata(a => a + 1, Right(1)) // 2
Either.cata(a => a + 1, Left(1)) // 2
Run a function on the value of both branches of an Either
and return an Either
Either.bimap(a => a + 1, Right(1)) // Right(2)
Either.bimap(a => a + 1, Left(1)) // Left(2)