option-t
Version:
A toolkit of Nullable/Option/Result type implementation in ECMAScript. Their APIs are inspired by Rust's `Option<T>` and `Result<T, E>`.
23 lines (22 loc) • 1.23 kB
JavaScript
import { ERR_MSG_TRANSFORMER_MUST_NOT_RETURN_NO_VAL_FOR_MAYBE, ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE_NO_VAL_FOR_MAYBE, } from './internal/error_message.js';
import { isNullOrUndefined, expectNotNullOrUndefined, } from './maybe.js';
/**
* Return the result of _transformer_ with using _input_ as an argument for it if _input_ is not `null` and `undefined`.
* Otherwise, return _defaultValue_.
*
* Basically, this operation is a combination `map()` and `unwrapOr()`.
*
* * `U` must not be `Maybe<*>`.
* * If the result of _transformer_ is `null` or `undefined`, this throw an `Error`.
* * If the result of _defaultValue_ is `null` or `undefined`, this throw an `Error`.
* * If you'd like to accept `Maybe<*>` as `U`, use a combination `andThen()` and `or()`.
*/
export async function mapOrAsyncForMaybe(input, defaultValue, transformer) {
if (isNullOrUndefined(input)) {
const nonNullDefault = expectNotNullOrUndefined(defaultValue, ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE_NO_VAL_FOR_MAYBE);
return nonNullDefault;
}
const result = await transformer(input);
const checked = expectNotNullOrUndefined(result, ERR_MSG_TRANSFORMER_MUST_NOT_RETURN_NO_VAL_FOR_MAYBE);
return checked;
}