$ npm install maybe
Maybe is a spiritual implementation of Haskell's Data.Maybe. Its purpose is to provide a useful monad around data which may or may not exist at runtime.
Node 0.8+ is supported. Older versions of Node may work, but are not targetted.
Detection of data absence can be on-trivial
typeof ; // => ""typeof null; // => "object"
Node.js indicates a datum's non-presence using a mixture of
references. At best, this adds unnecessarily to program complexity in handling these cases; at
worst, it discourages complete absence checks and leads to fault intolerance.
Maybe seeks to wrap data presence in a monad for handling such concerns. By using Maybe, you are declaring that your value may or may not exist when it is accessed. This encourages explicit handling of these cases, and ensures uniform treatment of such cases.
var Maybe = require'maybe';// The following are equivalenttrue;Maybetrue;
Maybe is most powerful when it wraps a function. Maybe will evaluate the function when its value is accessed, allowing for your control flow to interpret the state of some processing using simple Maybe data access.
var Maybe = require'maybe'start = Datenow;// We expect that our value function will return `true` after a 2 seconds have passed, and// otherwise will not return (return undefined)var unsure = Maybereturn Datenow > start + 2000 || ;;unsurevalue // => Maybe.NothingsetTimeoutunsurevalue 2000; // => true
Accesses the value wrapped by the Maybe, returning the value if it is present, or
if it is not.
Returns true if the Maybe's value is a
Maybe.Just type, indicating that it is known to exist.
Returns false if the Maybe's value is a
memoize on your maybe will ensure that its value function is only executed the first time
maybe.value(), and that its return value will be cached for all subsequest calls
var Maybe = require'maybe'unsure = Maybe /** ... */ ;unsurememoize;unsurevalue; // => will return data or `Maybe.Nothing` and will henceforth return that same result
A simple monadic type to represent a nonexistant value.
A simple monadic type representing a value that is known to exist.
var Maybe = require'maybe'unsure = MaybeMathrandom < 0.5 || ;unsurevalue; // => true|Maybe.Nothing
Maybe can wrap any literal value and handle its absence by returning a
While this is all well and good for data uniformity, the true power of Maybe comes when you use it to wrap a function. The function is evaluated each time the Maybe's value is accessed.
var Maybe = require'maybe'unsure = Maybe /** this may or may not return something */ ;for var i = 1000; i > 0; --iunsurevalue; // => will return a mixture of valid data and `Maybe.Nothing`
Please contribute! See the GitHub issues for project goals, feature discussion, and bug reports.
I would like to encourage all new code to include associated tests and jsdoc annotation. Thanks!