-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisMatch.js
58 lines (45 loc) · 1.58 KB
/
isMatch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Given an input string (s) and a pattern (p), implement wildcard pattern
// matching with support for '?' and '*'.
function isMatch(str, pattern) {
let strIndex = 0;
for (let patternIndex = 0; patternIndex < pattern.length; patternIndex++) {
const patternChar = pattern.charAt(patternIndex);
// strategy pattern for extensibility - support any operations besides "?" and "*"
if (strategiesMap[patternChar]) {
const nextStrIndex = strategiesMap[patternChar](str, pattern, strIndex, patternIndex);
if (nextStrIndex === -1) {
return false;
} else {
strIndex = nextStrIndex;
}
} else {
if (patternChar !== str.charAt(strIndex)) {
return false;
}
strIndex++;
}
}
return strIndex < str.length ? false : true;
}
const strategiesMap = {
"?": getNextStrIndexIfMatchSingleChar,
"*": getNextStrIndexIfMatchSegment,
}
function getNextStrIndexIfMatchSingleChar(str, pattern, strIndex, patternIndex) {
return typeof str.charAt(strIndex) === "" ? -1 : 1;
}
function getNextStrIndexIfMatchSegment(str, pattern, strIndex, patternIndex) {
const nextChar = pattern.charAt(patternIndex + 1);
if (nextChar === "") {
return str.length;
}
let currentStrIndex = strIndex;
while (str.charAt(currentStrIndex) !== "") {
if (str.charAt(currentStrIndex) === nextChar) {
return currentStrIndex;
}
currentStrIndex++;
}
return -1;
}
module.exports = isMatch;