giftbox
A lightweight Javascript library for the Option monad. Maybe there's something in it, maybe there isn't ;)
$ npm install giftbox
var Option = Option; ; // Some; // None; // 'hello world'; // 'pier piper'
Giftbox aims to provide a wrapper API around absent values and is highly motivated by Scala's Option.
One of big source of bugs in production environments is missing data represented by nulls, undefined, empty strings, etc. Traditionally calling methods on null
or 'empty' values causes NPE's, etc. and forces developers to create disorganized utilities with null/empty checks all over the codebase, adding further complexity.
Overview
Giftbox provides 3 simple classes to handle optional data - Option
, Some
& None
. Here's how to use them:
Simple Examples
Where Giftbox becomes powerful is when you have some logic that returns data and you need to handle that data:
var userDetails = ; if ; // A more functional form:; // Wrap a method return value in Option:var { return ;}; ;
Advanced Examples
Building a user subscription UI
// lets fetch a user; // then lets fetch their subscription record; // but what if they have no subscription?; // ok lets render what we got; // but what if there was no user?;
Finding Player Score
var { return ; // returns Option(user)}; var { return ; // returns Option(number)}; var { return score > 105}; ; // we don't want to render 'Some(103)'; // great, but we only want to show the score if it is above 105; None // but lets show a default value if player not found or // score not found or score not above 105; 'Lets start a new game here!'
API
Giftbox considers the following "absent" or "empty": null
, undefined
and NaN
.
isDefined
Returns true
if the val
is not empty.
;
get
Returns val
(whether or not it's empty).
;
getOrElse
Returns val
if it isDefined
otherwise returns elseval
.
;
orElse
Returns val
if it isDefined
otherwise uses alternative
as an Option
provider.
;
orNull
Returns val
if it isDefined
otherwise returns null
.
;
map
Maps val
if it isDefined
using the callback
function and returns Some(callback(val))
else returns None
;
;
flatMap
Flattens nested mapping calls over val
if it isDefined
using the callback
function and returns Some
else returns None
;
filter
Applies predicate
to val
if it isDefined
and returns Some(val)
if it passes and None
if it fails.
;
filterNot
Opposite of filter
.
;
foreach
Applies the callback
function to val
if it isDefined
and doesn't return anything.
;
match
Applies someCallback
on val
if it isDefined
otherwise applies noneCallback
.
;
collect
Applies predicate
on val
if it isDefined
and maps val
using callback
.
;
toArray
Transforms option to an array.
;
Contribution
Please contribute to Giftbox via GitHub issues. Would be great if all new code is submitted with tests and documentation. Lets discuss features and bugs there as well!