File tree Expand file tree Collapse file tree 2 files changed +58
-58
lines changed Expand file tree Collapse file tree 2 files changed +58
-58
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ *
3
+ *
4
+ *Implementation of the Boyer-Moore String Search Algo.
5
+ *The Boyer–Moore string search algorithm allows linear time in
6
+ * search by skipping
7
+ * indices when searching inside a string for a pattern.
8
+ *
9
+ *
10
+ *
11
+ *
12
+ **/
13
+ const buildBadMatchTable = ( str ) => {
14
+ let tableObj = { } ;
15
+ let strLength = str . length ;
16
+ for ( var i = 0 ; i < strLength - 1 ; i ++ ) {
17
+ tableObj [ str [ i ] ] = strLength - 1 - i ;
18
+ }
19
+ if ( tableObj [ str [ strLength - 1 ] ] == undefined ) {
20
+ tableObj [ str [ strLength - 1 ] ] = strLength ;
21
+ }
22
+ return tableObj ;
23
+ }
24
+
25
+
26
+ let boyerMoore = ( str , pattern ) => {
27
+ var badMatchTable = buildBadMatchTable ( pattern ) ,
28
+ offset = 0 ,
29
+ patternLastIndex = pattern . length - 1 ,
30
+ scanIndex = patternLastIndex ,
31
+ maxOffset = str . length - pattern . length ;
32
+ // if the offset is bigger than maxOffset, cannot be found
33
+ while ( offset <= maxOffset ) {
34
+ scanIndex = 0 ;
35
+ while ( pattern [ scanIndex ] == str [ scanIndex + offset ] ) {
36
+ if ( scanIndex == patternLastIndex ) {
37
+ // found at this index
38
+ return offset ;
39
+ }
40
+ scanIndex ++ ;
41
+ }
42
+ var badMatchString = str [ offset + patternLastIndex ] ;
43
+ if ( badMatchTable [ badMatchString ] ) {
44
+ // increase the offset if it exists
45
+ offset += badMatchTable [ badMatchString ]
46
+ } else {
47
+ offset += 1 ;
48
+ }
49
+ }
50
+ return - 1 ;
51
+ }
52
+ export { boyerMoore }
53
+
54
+
55
+
56
+
57
+
58
+
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments