UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

45 lines (43 loc) 966 B
import { dfdlT } from "@monstermann/dfdl"; //#region src/array/findIndexOrElse.ts /** * `findIndexOrElse(target, predicate, orElse)` * * Returns the index of the first element in `target` that satisfies the provided `predicate` function. If no element satisfies the predicate, calls `orElse` with the original array. * * ```ts * findIndexOrElse( * [1, 2, 3, 4], * (x) => x > 2, * () => -1, * ); // 2 * findIndexOrElse( * [1, 2, 3, 4], * (x) => x > 5, * (arr) => arr.length, * ); // 4 * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findIndexOrElse( * (x) => x > 2, * () => -1, * ), * ); // 2 * pipe( * [1, 2, 3, 4], * findIndexOrElse( * (x) => x > 5, * (arr) => arr.length, * ), * ); // 4 * ``` */ const findIndexOrElse = dfdlT((target, predicate, orElse) => { const idx = target.findIndex(predicate); return idx < 0 ? orElse(target) : idx; }, 3); //#endregion export { findIndexOrElse };