@lou.codes/predicates
Version:
🧐 Predicate util functions
29 lines (28 loc) • 868 B
JavaScript
import { attempt } from "@lou.codes/parsers";
import { isString } from "./isString.js";
/**
* Given a regular expression and a string, returns `true` if the string matches the regular expression.
*
* @category Primitives
* @example
* ```typescript
* const matchNumbers = match(/\d+/u);
*
* matchNumbers("123"); // true
* matchNumbers("abc"); // false
* ```
* @param regularExpression Instance of `RegExp` or a string.
* @returns `true` if the string matches the regular expression, `false` otherwise.
*/
export const match = regularExpression => {
const { flags, source } =
isString(regularExpression) ?
{
.../\/(?<source>.+)\/(?<flags>[gimsu])+$/u.exec(
regularExpression,
)?.groups,
}
: regularExpression;
const attemptTest = attempt(text => new RegExp(source, flags).test(text));
return text => attemptTest(text) ?? false;
};