Converts a nullable value to a Result
. null
and undefined
map to
Error
s, any other value maps to Ok
s.
forall a, b:
(a or None, b) => Result b a
& (a or None) => Result None a
Converts a nullable value to a Result
. null
and undefined
map to
Error
s, any other value maps to Ok
s.
A nullable is a value that may be any type, or null
/undefined
.
DEPRECATION WARNING:
In 2.0.x,nullableToResult
took only one parameter. This form of the function is now deprecated in favour of passing an explicit fallback value.
const nullableToResult = require('folktale/conversions/nullable-to-result');
const { Error, Ok } = require('folktale/result');
nullableToResult(undefined, 'error');
// ==> Error('error')
nullableToResult(null, 'error');
// ==> Error('error')
nullableToResult(1, 'error');
// ==> Ok(1)
function(a, givenFallback) {
const oldBehaviour = arguments.length < 2; // eslint-disable-line prefer-rest-params
if (oldBehaviour) {
deprecated(`nullableToResult(value) is being deprecated in favour of providing an explicit fallback value.
nullableToResult(value, fallback) is the new preferred form of this function.
`);
}
const fallback = oldBehaviour ? a : givenFallback;
return a != null ? Ok(a)
: /* else */ Error(fallback);
}