UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

31 lines (29 loc) 902 B
import { dfdlT } from "@monstermann/dfdl"; //#region src/string/matchOrElse.ts /** * `matchOrElse(target, source, orElse)` * * Returns the result of matching `target` string against `source` string or regular expression, or the result of calling `orElse` function with `target` if no match is found. * * ```ts * matchOrElse("hello world", "world", () => []); // ["world", index: 6, input: "hello world", groups: undefined] * matchOrElse("hello world", /\d+/, (str) => [str]); // ["hello world"] * ``` * * ```ts * pipe( * "hello world", * matchOrElse("world", () => []), * ); // ["world", index: 6, input: "hello world", groups: undefined] * * pipe( * "hello world", * matchOrElse(/\d+/, (str) => [str]), * ); // ["hello world"] * ``` */ const matchOrElse = dfdlT((target, source, orElse) => { return target.match(source) ?? orElse(target); }, 3); //#endregion export { matchOrElse };