Last active
February 6, 2023 18:46
-
-
Save daftAnorak/c8c8b56e44903d0eb7ca0d32885555e0 to your computer and use it in GitHub Desktop.
Code Exercise for JS position - Wildcard Matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Validates if given string matches given pattern | |
* @param {string} s - given string | |
* @param {string} p - given pattern | |
* @return {boolean} string matches pattern | |
*/ | |
function isMatch(s, p) { | |
let sIdx = 0; | |
let pIdx = 0; | |
// NOTE: set to -1 to allow for zero idx | |
let pIdxPostWildcardSeq = -1; | |
let sIdxPostWildcardSeq; | |
while (sIdx < s.length) { | |
// increment both idxs on character, or single-char-wildcard match | |
if (pIdx < p.length && (p[pIdx] === '?' || p[pIdx] === s[sIdx])) { | |
sIdx++; | |
pIdx++; | |
} | |
// increment pattern idx on variadic wildcard | |
// record both new idxs in case of preemptive mismatches on next loop | |
else if (pIdx < p.length && p[pIdx] === '*') { | |
pIdx++; | |
pIdxPostWildcardSeq = pIdx; | |
sIdxPostWildcardSeq = sIdx; | |
} | |
// if under variadic wildcard but not match: | |
// - increment post wildcard idx and reset string idx to it, | |
// - reset pattern idx BACK to just after wildcard | |
else if (pIdxPostWildcardSeq !== -1) { | |
sIdxPostWildcardSeq++; | |
sIdx = sIdxPostWildcardSeq; | |
pIdx = pIdxPostWildcardSeq; | |
} | |
// otherwise, pattern does not match -- fail! | |
else { | |
return false; | |
} | |
} | |
// handler for extraneous, variadic wildcards | |
// ex: `foobar` with `foo*r**` => true | |
while (pIdx < p.length && p[pIdx] === '*') { | |
pIdx++; | |
} | |
// matches if we've completely gone through all chars of pattern | |
return pIdx === p.length; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment