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.06 kB
import { isNotNull } from './nullable.js'; /** * Returns `null` if the _input_ is `null`, * otherwise calls _predicate_ with the _input_ `T` and returns: * * * `T` if _predicate_ returns `true`. * * `null` if _predicate_ returns `false`. */ export function filterForNullable(input, predicate) { if (isNotNull(input)) { const ok = predicate(input); if (ok) { return input; } } return null; } /** * Returns `null` if the _input_ is `null`, * 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. * * `null` if _predicate_ returns `false`. * * Please use {@link filterForNullable} generally if you don't have to narrow the type. */ export function filterWithEnsureTypeForNullable(input, predicate) { if (isNotNull(input)) { if (predicate(input)) { const result = input; return result; } } return null; }