UNPKG

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>`.

28 lines (27 loc) 1.28 kB
import { isNotNull, expectNotNull } from '../core/nullable.js'; import { ERR_MSG_TRANSFORMER_MUST_NOT_RETURN_NO_VAL_FOR_NULLABLE, ERR_MSG_RECOVERER_MUST_NOT_RETURN_NO_VAL_FOR_NULLABLE, } from '../internal/error_message.js'; /** * Return the result of _transformer_ with using _input_ as an argument for it if _input_ is not `null`. * Otherwise, return the result of _recoverer_. * * Basically, this operation is a combination `mapAsync()` and `unwrapOrElseAsync()`. * * * `U` must not be `Nullable<*>`. * * If the result of _transformer_ is `null`, this throw an `Error`. * * If the result of _recoverer_ is null`, this throw an `Error`. * * If you'd like to accept `Nullable<*>` as `U`, use a combination `andThenAsync()` and `orElseAsync()`. */ export async function mapOrElseAsyncForNullable(input, recoverer, transformer) { let result; let messageForExpect = ''; if (isNotNull(input)) { result = await transformer(input); messageForExpect = ERR_MSG_TRANSFORMER_MUST_NOT_RETURN_NO_VAL_FOR_NULLABLE; } else { result = await recoverer(); messageForExpect = ERR_MSG_RECOVERER_MUST_NOT_RETURN_NO_VAL_FOR_NULLABLE; } const checked = expectNotNull(result, messageForExpect); return checked; }