Option / Maybe implementation for union-type. See also union-type-either.
- Setoid
- Foldable
- Functor
- Apply
- Chain
- Applicative
- Monad
- Extract
Like Ramda, the functions in this lib take
the Opt
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 Opt = require('union-type-option')
var Some = Opt.Some
var None = Opt.None
Create an instance of Opt
with a non-null value.
Some(1) // Some(1)
Create an instance of Opt
with a null value.
None() // None()
Alias to get the instance of None()
Opt.none // None()
Compare the contained value of one Opt
against another using ===
.
Opt.equals(Some(1), Some(1)) //true
Opt.equals(Some({}), Some({})) //false
Opt.equals(None(), None()) //true
Run a function on a value in an Opt
and return new Opt with the result.
Opt.map(a => a + 3, Some(1)) // Some(4)
Run a predicate on a value in Opt
, if true the Some()
is returned, else None()
Opt.filter(a => a > 3, Some(2)) // None()
Opt.filter(a => a > 3, Some(4)) // Some(4)
Get the value out of an Opt
. May be null!
Opt.extract(Some(1)) // 1
Opt.extract(None()) // null
Put a value in an Opt
. Mostly useful for higher level operations.
Opt.of(1, None()) // Some(1)
Opt.of(1, Some(999)) // Some(1)
Run a function that returns an Opt
on the value in another Opt
.
var validLength = str => str.length < 8 ? None() : Some(str)
var validHasCapitals = str => (/[A-Z]/).test(str) ? Some(str) : None()
var validateUsername = username => Opt.chain(validHasCapitals, validLength(username))
Run a function inside an Opt
on the value in another Opt
Opt.ap(Some(2), Some(a => a * 2)) // Some(4)
Turn an option into something else by combining its value with a seed and a reducing function.
Opt.reduce((a, b) => a + b, 1, Some(2)) // Some(3)
Run a function on a Opt
and wrap result in another Opt
.
Opt.extend(Opt.map(a => a + 1), Some(1)) // Some(Some(2))