- ×
Maybe is a type that wraps optional values
Filed under miscellaneousShow AllMaybe
Maybe is a type that wraps optional values. It can either be a
Just
(has some value) or aNothing
(has no value).It's defined like this:
type Maybe<A> = Just<A> | Nothing
In JavaScript, it is a better way of handling
null
andundefined
. Instead of writing an if statement, ternary expression, or&&
shorthand to check if a value is present you can justmap
over it instead and assign the result of this expression or return it. You can also chain operations together, often leading to much cleaner code.It's inspired by Haskell's Maybe, Swift's Optional and Scala's Option.
Installation
Using yarn
$ yarn add maybes
or npm
$ npm install maybes
Usage
Import the library:
import { maybe } from 'maybes'
or if you want everything:
import { maybe, just, nothing } from 'maybes'
Use the
maybe
function to create aMaybe
from a value.const value = maybe(1) // Just(1) value.isJust() // true value.isNothing() // false
Use
map
to transform the value inside theMaybe
.value.map(v => v + 1) // Just(2)
Force unwrap the value with
just()
if it is present. Warning: this will throw an Error if it is aNothing
(has no value).value.just() // 1 (or throws Error)
Use the
maybe
function to wrap a possibly empty value.const empty = maybe(null) empty.isJust() // false empty.isNothing() // true empty.map(v => v + 1) // noop (No Operation) empty.just() // throws error
Use
orJust()
to provide a default value.empty.map(v => v.toUpperCase()).orJust('hello') // 'hello'
Use
orElse()
to provide a default already wrapped in a Maybe. This can be useful if you want to combine two or more Maybe's together.const hello = maybe('hello') empty.map(v => v.toUpperCase()).orElse(hello) // Maybe('hello')
Chain operations together using
map
:const m = maybe('Maybe ') const result = m .map(v => v.trim()) .map(v => v.toUpperCase()) // Just('MAYBE')
Use
flatMap
if you need to return aMaybe
in your closure instead of the value. For example, when you want to explicitly returnNothing
in a particular case.const a = maybe('hi') const result = a.flatMap(v => { if (v === 'hi') { return just('world') } else { return nothing } })
just
is a function likemaybe
that takes a value.nothing
is a reference toNothing
.Using
filter
is usually the best way to return aNothing
given a predicate. It returnsJust
only if there is a value and applying the predicate function to theMaybe
's value returnstrue
.const name = maybe(' ') const upper = name .map(v => v.trim()) .filter(v => v.length != 0) .map(v => v.toUpperCase())
Use
forEach
when you would otherwise usemap
but can't or don't want to return a value. This is usually when you are causing a side effect.forEach
returnsvoid
and so enforces it's the last in a chain. It runs only if there is a non empty value.maybe('effect').forEach(s => console.log(s))
Types
This library uses Flowtype so you can also import the
Maybe
type and use its definition:import { maybe } from 'maybes' import type { Maybe } from 'maybes' function getSomething(): Maybe<string> { return maybe('something') }
Don't worry if you don't use Flowtype though as it gets stripped by Babel.
Comparison with vanilla JavaScript
Ternary function that optionally calls another function called
transform
.Without Maybe
(value) ? transform(value) : null
(Safe version in case value is falsy, e.g.
0
)(value != null) ? transform(value) : null
With Maybe (handles falsy values like
0
and''
automatically).maybe(value).map(transform)
&& and || shorthand
Without Maybe
const object: ?Object = { value?: 'hello' } object && object.value && object.value.toUpperCase() || ''
With Maybe
maybe(object).flatMap(o => maybe(o.value).map(v => v.toUpperCase())).orJust('')
With types already converted to
Maybe
's.const object = maybe({ value: maybe('hello') }) object.flatMap(o => o.value.map(v => v.toUpperCase())).orJust('')
License
Maybe is available under the MIT license. See LICENSE.