A value, a zero-argument factory, or an existing Maybe.
A Maybe monad wrapping the resolved value.
// Wrap a plain value
maybe(42).value; // 42
// Wrap a factory – nullish return becomes empty
maybe(() => null).empty; // true
// Pass-through an existing Maybe
const m = maybe(42);
maybe(m) === m; // true
// Errors thrown in a factory become error monads
maybe(() => { throw new Error('!'); }).error; // Error: !
// Nullish init becomes empty
maybe(undefined).empty; // true
Return the shared empty monad singleton — an empty monad with no
associated error.
Because there is no error, catch is a no-op on this monad; use else to
provide a fallback instead. All calls return the same instance.
The shared empty Maybe singleton.
Create an empty monad carrying an error.
If error is omitted or nullish, a generic Error('unknown') is used so
the monad always has a non-nullish error property. Use this variant
(rather than maybe.empty) when you want downstream catch handlers
to run.
Optionalerror: unknownThe error value to associate with the monad. Defaults to
new Error('unknown') when omitted.
An empty Maybe carrying the given error.
const m = maybe.error(new TypeError('bad input'));
m.ok; // false
m.empty; // true
m.error; // TypeError: bad input
// Recover with catch
m.catch((err) => `Handled: ${err.message}`).value;
// 'Handled: bad input'
// catch is a no-op on maybe.empty() (error is null)
maybe.empty().catch(() => 'x').ok; // false
Create a Maybe monad from a value, a factory function, or an existing
Maybe.initis already aMaybe, it is returned as-is.initis a function, it is called and its return value is wrapped.nullorundefined, an empty monad is returned (equivalent to maybe.empty).