(str: string, pattern: string)
| 1 | import { sortBy, pipe } from "remeda" |
| 2 | |
| 3 | export function match(str: string, pattern: string) { |
| 4 | if (str) str = str.replaceAll("\\", "/") |
| 5 | if (pattern) pattern = pattern.replaceAll("\\", "/") |
| 6 | let escaped = pattern |
| 7 | .replace(/[.+^${}()|[\]\\]/g, "\\$&") // escape special regex chars |
| 8 | .replace(/\*/g, ".*") // * becomes .* |
| 9 | .replace(/\?/g, ".") // ? becomes . |
| 10 | |
| 11 | // If pattern ends with " *" (space + wildcard), make the trailing part optional |
| 12 | // This allows "ls *" to match both "ls" and "ls -la" |
| 13 | if (escaped.endsWith(" .*")) { |
| 14 | escaped = escaped.slice(0, -3) + "( .*)?" |
| 15 | } |
| 16 | |
| 17 | const flags = process.platform === "win32" ? "si" : "s" |
| 18 | return new RegExp("^" + escaped + "$", flags).test(str) |
| 19 | } |
| 20 | |
| 21 | export function all(input: string, patterns: Record<string, any>) { |
| 22 | const sorted = pipe(patterns, Object.entries, sortBy([([key]) => key.length, "asc"], [([key]) => key, "asc"])) |
no outgoing calls
no test coverage detected