Guest User

Untitled

a guest
Feb 15th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. function matcher(s, p) {
  2. let matches = true;
  3. let i = 0;
  4.  
  5. s = s.split('');
  6. p = p.split('');
  7. for (let j = 0; j < p.length; j++){
  8. // Letter, no asteriks
  9. if (p[j] !== '.' && p[j+1] !== '*'){
  10. if (s[i] !== p[j]){
  11. console.log(`letter, no asteriks: ${s[i]} != ${p[j]}`)
  12. matches = false;
  13. break;
  14. }
  15. i += 1;
  16. continue;
  17. }
  18.  
  19. // Letter, asteriks
  20. if (p[j] !== '.' && p[j+1] === '*'){
  21. if (s[i] !== p[j]){
  22. console.log(`letter, asteriks: ${s[i]} != ${p[j]}`)
  23. matches = false;
  24. break;
  25. }
  26. while (s[i] === p[j]){
  27. i += 1;
  28. }
  29. j += 1; // Accomodate for asteriks
  30. continue;
  31. }
  32.  
  33. // Dot, no asteriks
  34. if (p[j] === '.' && p[j+1] !== '*'){
  35. if (i >= s.length){
  36. console.log(`dot, not asteriks: ${i}>=${s.length}`)
  37. matches = false;
  38. break;
  39. }
  40. i += 1;
  41. continue;
  42. }
  43.  
  44. // Dot, asteriks
  45. else if (p[j] === '.' && p[j+1] === '*'){
  46. if (i >= s.length){
  47. console.log(`dot, asteriks: ${i}>=${s.length}`)
  48. matches = false;
  49. break;
  50. }
  51. let current = s[i]
  52. while (s[i] === current){
  53. i += 1;
  54. }
  55. j += 1; // Accomodate for asteriks
  56. continue;
  57. }
  58. }
  59.  
  60. // More string left to match not covered by pattern
  61. if (i < s.length) {
  62. console.log(`whole string not matched: ${i} < ${s.length}`)
  63. matches = false;
  64. }
  65.  
  66. return matches
  67. }
  68.  
  69. console.log(matcher("abcd", "abcdefg")) //false
  70. console.log(matcher("abcd", "abc")); //false
  71. console.log(matcher("abc", "abc")); //true
  72. console.log(matcher("zabc", ".abc")); //true
  73. console.log(matcher("abc", ".*")); //false
  74. console.log(matcher("abbbbbbcd", "a.*cd")); //true
  75. console.log(matcher("abbfbbbcd", "a.*cd")); //false
  76. console.log(matcher("aaccbbhhhhhh", "a*c*b*f*")); //false
Add Comment
Please, Sign In to add comment