Skip to content

Commit b8a8edc

Browse files
committed
Update index.ts
1 parent 4ccb4be commit b8a8edc

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

wildcard-matching/index.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ export default function isMatch(s: string, p: string): boolean {
66
const words = p.split(/\*+/g);
77
// console.log(words);
88

9-
if (words.length === 1) {
10-
return check_regular(s, p);
11-
}
129
if (words.length === 2 && words[0] === "" && words[1] === "") {
1310
return true;
1411
}
12+
if (
13+
words.length === 1 ||
14+
(words.length === 2 && (words[0] === "" || words[1] === ""))
15+
) {
16+
return check_regular(s, p);
17+
}
1518
if (!check_includes(s, p)) return false;
1619
if (words.length >= 2) {
1720
return check_fixs(s, words);
@@ -21,7 +24,6 @@ export default function isMatch(s: string, p: string): boolean {
2124
}
2225
function check_includes(s: string, p: string) {
2326
const words = Array.from(new Set(p.split(/\?|\*+/g).filter(Boolean)));
24-
2527
if (
2628
words.some((word) => {
2729
return !s.includes(word);
@@ -40,15 +42,15 @@ function check_fixs(s: string, words: string[]): boolean {
4042
if (suffix) {
4143
const matched = str.match(
4244
//@ts-ignore
43-
new RegExp(`^(.*?)${suffix.replaceAll("?", ".")}$`),
45+
new RegExp(`^(.*?)${suffix.replaceAll("?", ".")}$`)
4446
);
4547
if (!matched) return false;
4648
str = matched[1];
4749
}
4850
if (prefix) {
4951
const matched = str.match(
5052
//@ts-ignore
51-
new RegExp(`^${prefix.replaceAll("?", ".")}(.*?)$`),
53+
new RegExp(`^${prefix.replaceAll("?", ".")}(.*?)$`)
5254
);
5355
if (!matched) return false;
5456
str = matched[1];
@@ -62,22 +64,22 @@ function check_regular(s: string, p: string): boolean {
6264
// console.log("check_regular", s, p);
6365
return new RegExp(
6466
//@ts-ignore
65-
"^" + p.replaceAll("?", ".") + "$",
66-
"g",
67+
"^" + p.replaceAll("?", ".").replaceAll(/\*+/g, ".*") + "$",
68+
"g"
6769
).test(s);
6870
}
6971
function check_words(s: string, words: string[]): boolean {
7072
// console.log("check_words", s, words);
7173
if (words.length === 0) return true;
7274
const mid_index = words.reduce(
7375
(a, v, i) => (v.length > words[a].length ? i : a),
74-
Math.floor(words.length / 2),
76+
Math.floor(words.length / 2)
7577
);
7678
// const mid_index = Math.floor(words.length / 2);
7779
const middle = words[mid_index];
7880
const matched_array = Array.from(
7981
//@ts-ignore
80-
s.matchAll(new RegExp(`${middle.replaceAll("?", ".")}`, "g")),
82+
s.matchAll(new RegExp(`${middle.replaceAll("?", ".")}`, "g"))
8183
);
8284

8385
// console.log(matched_array);

0 commit comments

Comments
 (0)