Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function matcher(s, p) {
- let matches = true;
- let i = 0;
- s = s.split('');
- p = p.split('');
- for (let j = 0; j < p.length; j++){
- // Letter, no asteriks
- if (p[j] !== '.' && p[j+1] !== '*'){
- if (s[i] !== p[j]){
- console.log(`letter, no asteriks: ${s[i]} != ${p[j]}`)
- matches = false;
- break;
- }
- i += 1;
- continue;
- }
- // Letter, asteriks
- if (p[j] !== '.' && p[j+1] === '*'){
- if (s[i] !== p[j]){
- console.log(`letter, asteriks: ${s[i]} != ${p[j]}`)
- matches = false;
- break;
- }
- while (s[i] === p[j]){
- i += 1;
- }
- j += 1; // Accomodate for asteriks
- continue;
- }
- // Dot, no asteriks
- if (p[j] === '.' && p[j+1] !== '*'){
- if (i >= s.length){
- console.log(`dot, not asteriks: ${i}>=${s.length}`)
- matches = false;
- break;
- }
- i += 1;
- continue;
- }
- // Dot, asteriks
- else if (p[j] === '.' && p[j+1] === '*'){
- if (i >= s.length){
- console.log(`dot, asteriks: ${i}>=${s.length}`)
- matches = false;
- break;
- }
- let current = s[i]
- while (s[i] === current){
- i += 1;
- }
- j += 1; // Accomodate for asteriks
- continue;
- }
- }
- // More string left to match not covered by pattern
- if (i < s.length) {
- console.log(`whole string not matched: ${i} < ${s.length}`)
- matches = false;
- }
- return matches
- }
- console.log(matcher("abcd", "abcdefg")) //false
- console.log(matcher("abcd", "abc")); //false
- console.log(matcher("abc", "abc")); //true
- console.log(matcher("zabc", ".abc")); //true
- console.log(matcher("abc", ".*")); //false
- console.log(matcher("abbbbbbcd", "a.*cd")); //true
- console.log(matcher("abbfbbbcd", "a.*cd")); //false
- console.log(matcher("aaccbbhhhhhh", "a*c*b*f*")); //false
Add Comment
Please, Sign In to add comment