@monstermann/fn
Version:
A utility library for TypeScript.
32 lines (30 loc) • 829 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/string/lastIndexOfOrElse.ts
/**
* `lastIndexOfOrElse(target, source, orElse)`
*
* Returns the index of the last occurrence of `source` string in `target` string, or the result of calling `orElse` function with `target` if not found.
*
* ```ts
* lastIndexOfOrElse("hello world hello", "hello", () => -1); // 12
* lastIndexOfOrElse("hello world", "foo", (str) => str.length); // 11
* ```
*
* ```ts
* pipe(
* "hello world hello",
* lastIndexOfOrElse("hello", () => -1),
* ); // 12
*
* pipe(
* "hello world",
* lastIndexOfOrElse("foo", (str) => str.length),
* ); // 11
* ```
*/
const lastIndexOfOrElse = dfdlT((a, b, orElse) => {
const idx = a.lastIndexOf(b);
return Number.isFinite(idx) ? idx : orElse(a);
}, 3);
//#endregion
export { lastIndexOfOrElse };