Last active
January 1, 2016 06:29
-
-
Save videlalvaro/8105837 to your computer and use it in GitHub Desktop.
This is a vanilla shift_and implementation in JS. Lacking the context it's hard to see what's going on. The interesting part of the algorithm is the bit parallelism techniques it uses to match prefixes. The implementation is based on this book: http://www.amazon.com/Flexible-Pattern-Matching-Strings-Algorithms/dp/0521039932/ Blog post explaining…
This file contains hidden or 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
| /** | |
| * string p: pattern to search (needle); | |
| * string text: haystack | |
| **/ | |
| function shift_and(p, text) { | |
| var b = {}; | |
| var l = p.length; | |
| var tl = text.length; | |
| // initialize bitmask table | |
| for (var i = 0; i < l; i++) { | |
| var ch = p.charAt(i); | |
| b[ch] = 0; | |
| } | |
| //build bitmask table; | |
| for (var i = 0; i < l; i++) { | |
| b[p.charAt(i)] = b[p.charAt(i)] | (1 << i); | |
| } | |
| var d = 0; | |
| var matchMask = << l-1; | |
| for (var i = 0; i < tl; i++) { | |
| d = ((d << 1) | 1) & (b[text.charAt(i)] | 0); | |
| var matched = (d & matchMask); | |
| if (matched != 0) { | |
| return i - l + 1; | |
| } | |
| } | |
| return -1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment