plain implementation of Maybe (Optional, Nullable) monad
Can you spot the error?
const userA = name: 'Basha' pet: nullconst userB = name: 'Cheyenne' pet: name: 'Adonis' species: 'cat'const users = userA userBusers// * this will give us a null reference error!// TypeError: Cannot read property 'name' of null
Instead, we could enclose the assumption that the user has a pet using Nullable:
const Nullable =users// => 'Hi Basha!'// => 'Hi Cheyenne and Adonis the cat!'
We can do some other things with Nullables, too:
const foo =console// => 10foo// => '??'foo// => 23
Depending on your background, you may also know this as
Nullable works similar to
Promises, in that it is a container datatype which wraps a value which may be null, or else have a value.
The idea is that all operations and transformations that are done on this value should only happen once and if the value is not null - and if it is, we can avoid explicit and error-prone manual null checking.
If you're sick of seeing errors like
Uncaught TypeError: Cannot read property 'name' of null in your programs, I encourage you to use
You may use Nullables as a functional utility library, like you might
lodash, or you can model your objects with nullables so you may call methods directly.
The general pattern is:
Nullable#map(). Calling this always returns another Nullalbe, like how
Promise#then()always returns another Promise.
orDefault(val), providing a default value.
This follows the same general pattern as Promises: wrap - map - ** unwrap**
Constructor, may be called with or without
** also aliased as Nullable.of and Nullable#of (both static and instance methods) **
Map a function
fn to the value if available. Returns a Nullable of the return type of
fn. Analogous to
Call a method on the underlying value if available. Returns a Nullable of the return type of the method. Additional parameters are optional and work like
Returns the underlying value if available, or the default argument specified.
** this method is also aliased as
Nullable<T>#orElse, which may feel more intuitive to you **
It is preferable to interact with Nullable via the
orDefault methods, but the following properties are exposed. Using them, and especially changing them, can make your programs more error-prone and harder to understand and reason about. Caveat utilitor.
Access the underlying value, if available. May be
$ npm install nullable
From package root:
$ npm install $ npm test
ISC. (c) MMXVI email@example.com. See LICENSE.md