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>`.
78 lines (77 loc) • 2.08 kB
JavaScript
import { ERR_MSG_UNWRAP_ERR_BUT_INPUT_IS_OK, ERR_MSG_UNWRAP_OK_BUT_INPUT_IS_ERR, } from '../internal/error_message.js';
export function isOk(input) {
return input.ok;
}
export function createOk(val) {
const r = {
ok: true,
val,
// XXX:
// We need to fill with `null` to improve the compatibility with Next.js
// see https://github.com/option-t/option-t/pull/1256
err: null,
};
return r;
}
export function isErr(input) {
return !input.ok;
}
export function createErr(err) {
const r = {
ok: false,
// XXX:
// We need to fill with `null` to improve the compatibility with Next.js
// see https://github.com/option-t/option-t/pull/1256
val: null,
err,
};
return r;
}
/**
* Return the inner `T` of a `Ok(T)`.
*
* @throws {TypeError}
* Throws if the self is a `Err`.
*/
export function unwrapOk(input) {
return expectOk(input, ERR_MSG_UNWRAP_OK_BUT_INPUT_IS_ERR);
}
/**
* Return the inner `E` of a `Err(E)`.
*
* @throws {TypeError}
* Throws if the self is a `Ok`.
*/
export function unwrapErr(input) {
return expectErr(input, ERR_MSG_UNWRAP_ERR_BUT_INPUT_IS_OK);
}
/**
* Return _input_ as `T` if the passed _input_ is `Ok(T)`.
* Otherwise, throw `TypeError` with the passed `msg`.
*
* @throws {TypeError}
* Throws if the self is a `Err`.
*/
export function expectOk(input, msg) {
if (isErr(input)) {
throw new TypeError(msg);
}
// We access the property directly to make this operator is a primitive basic operator.
const val = input.val;
return val;
}
/**
* Return _input_ as `E` if the passed _input_ is `Err(E)`.
* Otherwise, throw `TypeError` with the passed `msg`.
*
* @throws {TypeError}
* Throws if the self is a `Ok`.
*/
export function expectErr(input, msg) {
if (isOk(input)) {
throw new TypeError(msg);
}
// We access the property directly to make this operator is a primitive basic operator.
const err = input.err;
return err;
}