Optional data structure is based on Rust Option
enum. It removes the hassle of
checking for null
or undefined
in your code and provides set of useful methods
for dealing with potentially missing data.
import {
None,
Some,
Optional,
} from '@bausano/data-structures'
const none: Optional<number> = new None
const some: Optional<number> = none.or(new Some(3))
-
isSome () : boolean
Determines whether the option wraps any value (is instance ofSome
). -
isNone () : boolean
Determines whether the option has no value (is instance ofNone
). -
unwrap () : T
Returns the value or throws an exception if the option isNone
. -
unwrapOr (def: T) : T
If the option isSome
, returns the value, otherwise return thedef
. -
unwrapOrElse (closure: () => T) : T
If the option isSome
, returns the value, otherwise computes theclosure
and returns the result. -
expect (e: Error) : T
If the option isSome
, return it. Otherwise, throws the errore
. -
filter (predicate: (t: T) => boolean) : Optional<T>
ReturnsNone
if the option isNone
, otherwise calls predicate with the value and returnsSome
if the predicate returnstrue
, orNone
if the predicate returnsfalse
. -
map<U, V> (u: Optional<U>, predicate: (t: T, u: U) => Optional<V>) : Optional<V>
Maps this optional to the other one. If either option isNone
, returnsNone
as well. Otherwise, returns the result of the predicate. -
mapOr<U> (predicate: (t: T) => U, def: U) : U
MapsT
to the typeU
or defaults if option isNone
. -
mapOrElse<U> (predicate: (t: T) => U, closure: () => U) : U
MapsT
to the typeU
or defaults if option isNone
. -
match (some: (t: T) => void, none: () => void) : void
If option isNone
, matches second callback, otherwise passes option value to the first callback. -
matchSome (closure: (t: T) => void) : void
Runs the closure if optional isSome
. -
matchNone (closure: () => void) : void
Runs the closure if optional isNone
. -
andThen<U> (closure: (t: T) => Optional<U>) : Optional<U>
Mutates theOptional
's wrapped value into a new type. -
or (def: Optional<T>) : Optional<T>
If this optional isNone
, returnsdef
, otherwise returnsthis
. -
orElse (closure: () => Optional<T>) : Optional<T>
If this optional isNone
, returnsdef
, otherwise returnsthis
.
When using optionals as class properties, in order to change the value of the optional, you have to instantiate a new object, meaning any reference to the previous optional will still point to the old value.