Optionull
Basic Implementation for Optional/Nullables in Javascript
Table of Contents
Installation
npm install --save optionull
Optional Class
<!-- In the browser -->
const Optional = Optional;// orconst Optional = ;// or;
ofNullable(value)
Creates and returns a new optional with the value provided.
const opt = Optional; //this is basically an empty optional.const nullOpt = Optional;
empty()
Creates and returns a new optional with empty value.
const emptyOpt = Optional;
isDefined()
Returns true if the value is defined.
opt; // truenullOpt; // also true emptyOpt; // falseOptional; // false
isNotNull()
Returns true if the value is not null.
opt; // truenullOpt; // false emptyOpt; // trueOptional; // true
isPresent()
Returns true if the value defined and not null.
opt; // truenullOpt; // false emptyOpt; // falseOptional; // false
ifPresent(fn)
Calls the function fn if the value is present.
opt; // prints 'somevalue' in the console emptyOpt; // nothing happens
ifPresentOrElse(fn, elseFn)
Calls the function fn if the value is present, otherwise calls the function elseFn.
opt; // prints 'found' in the console emptyOpt; // prints 'not found' in the console
getOrElse(fnOrVal)
Returns the value if present. Otherwise returns the value of fnOrVal.
opt; // returns 'somevalue' emptyOpt; // returns 'someother value'emptyOpt; // returns 'someother value'
get()
Returns the value of the optional. (Could be null or undefined)
opt; // 'somevalue'emptyOpt; // undefinednullOpt; // null
map(fn)
If the value is present, applies the mapping function and returns its result wrapped in a new optional. Returns empty optional otherwise.
opt; // 9opt; // 'somevalue' (note the original optional did not change) emptyOpt; // false
flatMap(fn)
If the value is present, applies the mapping function then if the function returns optional the optional is returned else the result is wrapped in a new optional and returned. Return empty optional if the value is not present.
opt; // 9opt; // 9
filter(fnOrVal)
Returns the value wrapped in a new optional if the value is preset and the value matches the parameter or the parameter function returns truthy value. Returns an empty optional if the value is not present or the parameter function returns a falsy value or the value did not match the paramter.
opt; // somevalueopt; // somevalueopt; // falseopt; //false