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>`.
47 lines (46 loc) • 1.11 kB
JavaScript
import { ERR_MSG_UNWRAP_SOME_BUT_INPUT_IS_NONE } from './internal/error_message.js';
export function isSome(input) {
return input.ok;
}
export function createSome(val) {
const r = {
ok: true,
val,
};
return r;
}
export function isNone(input) {
return !input.ok;
}
export function createNone() {
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,
};
return r;
}
/**
* Return the inner `T` of a `Some(T)`.
*
* @throws {TypeError}
* Throws if the self is a `None`.
*/
export function unwrapSome(input) {
return expectSome(input, ERR_MSG_UNWRAP_SOME_BUT_INPUT_IS_NONE);
}
/**
* Return _input_ as `T` if the passed _input_ is `Some(T)`.
* Otherwise, throw `TypeError` with the passed `msg`.
*
* @throws {TypeError}
* Throws if the self is a `None`.
*/
export function expectSome(input, msg) {
if (!input.ok) {
throw new TypeError(msg);
}
return input.val;
}