UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

32 lines (30 loc) 780 B
import { dfdlT } from "@monstermann/dfdl"; //#region src/string/indexOfOrElse.ts /** * `indexOfOrElse(target, source, orElse)` * * Returns the index of the first occurrence of `source` string in `target` string, or the result of calling `orElse` function with `target` if not found. * * ```ts * indexOfOrElse("hello world", "world", () => -1); // 6 * indexOfOrElse("hello world", "foo", (str) => str.length); // 11 * ``` * * ```ts * pipe( * "hello world", * indexOfOrElse("world", () => -1), * ); // 6 * * pipe( * "hello world", * indexOfOrElse("foo", (str) => str.length), * ); // 11 * ``` */ const indexOfOrElse = dfdlT((a, b, orElse) => { const idx = a.indexOf(b); return Number.isFinite(idx) ? idx : orElse(a); }, 3); //#endregion export { indexOfOrElse };