Maybe
folktale.maybe
- Models either a value or nothing.
- Allows distinction between an explicit null value (
nullwas returned). and an implicitnullvalue (nothing was returned). - It is a Monad as it has a
chainproperty. - It will be either a value:
Maybe.Just, or no value:Maybe.Nothing. - If a
Maybe.Justvalue will be stored in thevalueproperty. - Will have either an
isJustorisNothingproperty, but these are deprecated. - Allows distinction between an explicit null value (
nullwas returned). and an implicitnullvalue (nothing was returned).
Creation
Maybe.Just(value);
Maybe.Nothing();
Extracting Result
getOrElse
It also offers a getOrElse method which can be used for extracting a value with a default if the result is an error:
const value = maybe.getOrElse(DEFAULT_VALUE);
Transformation
matchWith
To map the result to a different function depending on whether it is a Result.Ok or a Result.Error:
maybe.matchWith({
Just: ({value}) => `Value: ${value}`,
Nothing: () => `No value`,
})
map
To perform an action on the result only if it is OK, map can be used. If the result is a Maybe.Nothing, it will just return that Maybe.Nothing, but if the result is Maybe.Just, its value will be passed in to the function supplied, and it will return whatever the function returns as the value of a Maybe.Just.
const value = maybe.map(example);
chain
However, if the function supplied to map also returns a Maybe, chain should be used instead to avoid a nested Maybe. In this case it is assumed that the value returned will be a Maybe, so whatever is returned from the function is returned as is, without being wrapped in a Maybe.
const value = maybe.chain(example);
orElse
To perform an action on the result only if it is Nothing, orElse_ can be used. _If the result is a Maybe.Just, it will just return that Maybe.Just, but if the result is Maybe.Nothing, its value will be passed in to the function supplied, and it will return whatever the function returns. For consistency, it should return a Maybe unless it throws.
const value = result.orElse(example);Checking Type
Introspection
To devine whether a Maybe is a Just or a Nothing , hasInstance is used:
Maybe.Just.hasInstance(result);
Maybe.Nothing.hasInstance(result);
Example
const a = range(1,3);
const alpha = (value) => {
const result = contains(value, a) ?
Maybe.Just(value) :
Maybe.Nothing();
return result;
}
const hasValue = alpha(2);
const noValue = alpha(3);
console.log('Has Value: ', hasValue.value); // 2
console.log('Has Value - is Maybe.Just: ', Maybe.Just.hasInstance(hasValue)); // true
console.log('Has Value - is Maybe.Nothing: ', Maybe.Nothing.hasInstance(hasValue)); // false
console.log('No Value: ', noValue); // Nothing
console.log('No Value - is Maybe.Just: ', Maybe.Just.hasInstance(noValue)); // false
console.log('No Value - is Maybe.Nothing: ', Maybe.Nothing.hasInstance(noValue)); // true