|
| 1 | +function isMatch(str, pat) { |
| 2 | + return recursiveIsMatch(0, 0, str, pat); |
| 3 | +} |
| 4 | +function recursiveIsMatch(i, j, str, pat) { |
| 5 | + const inputStringLength = str.length; |
| 6 | + const patternLength = pat.length; |
| 7 | + |
| 8 | + // Reached the end of the pattern |
| 9 | + if (j == patternLength) { |
| 10 | + // Return whether or not we've also reached the end of the string (entire string has passed) |
| 11 | + return i == inputStringLength; |
| 12 | + } |
| 13 | + |
| 14 | + // If the current pattern character is followed by a * (is a wildcard) |
| 15 | + if (j + 1 < patternLength && pat.charAt(j + 1) == '*') { |
| 16 | + // Assume 0 matches of the current pattern character, move on to the next point in the pattern (after the asterisk) |
| 17 | + if (recursiveIsMatch(i, j + 2, str, pat)) return true; |
| 18 | + |
| 19 | + // Loop through the remaining characters, so long as they match by character (or .) |
| 20 | + while ( |
| 21 | + i < inputStringLength && |
| 22 | + (pat.charAt(j) == '.' || str.charAt(i) == pat.charAt(j)) |
| 23 | + ) { |
| 24 | + // Check the rest of the string (1 character forward), against the next point in the pattern (after the asterisk) |
| 25 | + if (recursiveIsMatch(++i, j + 2, str, pat)) return true; |
| 26 | + } |
| 27 | + } |
| 28 | + // If the current pattern character is not a wildcard, and matches the current string character |
| 29 | + else if ( |
| 30 | + i < inputStringLength && |
| 31 | + (pat.charAt(j) == '.' || str.charAt(i) == pat.charAt(j)) |
| 32 | + ) { |
| 33 | + // Move onto the next character, and the next character of the pattern |
| 34 | + return recursiveIsMatch(i + 1, j + 1, str, pat); |
| 35 | + } |
| 36 | + |
| 37 | + // String does not match current point in pattern |
| 38 | + return false; |
| 39 | +} |
0 commit comments