UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

33 lines (31 loc) 915 B
import { FnError } from "../function/FnError.js"; import { dfdlT } from "@monstermann/dfdl"; //#region src/array/findIndexOrThrow.ts /** * `findIndexOrThrow(target, predicate)` * * Returns the index of the first element in `target` that satisfies the provided `predicate` function. If no element satisfies the predicate, throws an error. * * ```ts * findIndexOrThrow([1, 2, 3, 4], (x) => x > 2); // 2 * findIndexOrThrow([1, 2, 3, 4], (x) => x > 5); // throws FnError * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findIndexOrThrow((x) => x > 2), * ); // 2 * pipe( * [1, 2, 3, 4], * findIndexOrThrow((x) => x > 5), * ); // throws FnError * ``` */ const findIndexOrThrow = dfdlT((target, predicate) => { const idx = target.findIndex(predicate); if (idx < 0) throw new FnError("Array.findIndexOrThrow: No value found.", [target, predicate]); return idx; }, 2); //#endregion export { findIndexOrThrow };