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

36 lines (35 loc) 1.14 kB
import { isNotUndefined } from '../core/undefinable.js'; /** * Returns `undefined` if the _input_ is `undefined`, * otherwise calls _predicate_ with the _input_ `T` and returns: * * * `T` if _predicate_ returns `true`. * * `undefined` if _predicate_ returns `false`. */ export function filterForUndefinable(input, predicate) { if (isNotUndefined(input)) { const ok = predicate(input); if (ok) { return input; } } return undefined; } /** * Returns `undefined` if the _input_ is `undefined`, * otherwise calls _predicate_ with the _input_ `T` and returns: * * * The input value as `U` if _predicate_ returns `true` which means that _predicate_ says the input value is U. * * `undefined` if _predicate_ returns `false`. * * Please use {@link filterForUndefinable} generally if you don't have to narrow the type. */ export function filterWithEnsureTypeForUndefinable(input, predicate) { if (isNotUndefined(input)) { if (predicate(input)) { const result = input; return result; } } return undefined; }