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>`.
18 lines (17 loc) • 784 B
JavaScript
import { isOk } from '../core/result.js';
import { unsafeUnwrapValueInErrWithoutAnyCheck, unsafeUnwrapValueInOkWithoutAnyCheck, } from '../internal/intrinsics_unsafe.js';
/**
* Maps a `Result<T, E>` to `U` by applying _transformer_ to a contained `Ok(T)` value in _input_,
* or a _recoverer_ function to a contained `Err(E)` value in _input_.
* This function can be used to unpack a successful result while handling an error.
*/
export function mapOrElseForResult(input, recoverer, transformer) {
if (isOk(input)) {
const val = unsafeUnwrapValueInOkWithoutAnyCheck(input);
const result = transformer(val);
return result;
}
const err = unsafeUnwrapValueInErrWithoutAnyCheck(input);
const fallback = recoverer(err);
return fallback;
}