|
11 | 11 | * |
12 | 12 | **/ |
13 | 13 | const buildBadMatchTable = (str) => { |
14 | | - const tableObj = {}; |
15 | | - const strLength = str.length; |
| 14 | + const tableObj = {} |
| 15 | + const strLength = str.length |
16 | 16 | for (let i = 0; i < strLength - 1; i++) { |
17 | | - tableObj[str[i]] = strLength - 1 - i; |
| 17 | + tableObj[str[i]] = strLength - 1 - i |
18 | 18 | } |
19 | 19 | if (tableObj[str[strLength - 1]] === undefined) { |
20 | | - tableObj[str[strLength - 1]] = strLength; |
| 20 | + tableObj[str[strLength - 1]] = strLength |
21 | 21 | } |
22 | | - return tableObj; |
| 22 | + return tableObj |
23 | 23 | } |
24 | 24 |
|
25 | | - |
26 | 25 | const boyerMoore = (str, pattern) => { |
27 | | - let badMatchTable = buildBadMatchTable(pattern); |
28 | | - let offset = 0; |
29 | | - let patternLastIndex = pattern.length - 1; |
30 | | - let scanIndex = patternLastIndex; |
31 | | - let maxOffset = str.length - pattern.length; |
| 26 | + const badMatchTable = buildBadMatchTable(pattern) |
| 27 | + let offset = 0 |
| 28 | + const patternLastIndex = pattern.length - 1 |
| 29 | + let scanIndex = patternLastIndex |
| 30 | + const maxOffset = str.length - pattern.length |
32 | 31 | // if the offset is bigger than maxOffset, cannot be found |
33 | 32 | 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 | | - const 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 | | - } |
| 33 | + scanIndex = 0 |
| 34 | + while (pattern[scanIndex] === str[scanIndex + offset]) { |
| 35 | + if (scanIndex === patternLastIndex) { |
| 36 | + // found at this index |
| 37 | + return offset |
| 38 | + } |
| 39 | + scanIndex++ |
| 40 | + } |
| 41 | + const badMatchString = str[offset + patternLastIndex] |
| 42 | + if (badMatchTable[badMatchString]) { |
| 43 | + // increase the offset if it exists |
| 44 | + offset += badMatchTable[badMatchString] |
| 45 | + } else { |
| 46 | + offset += 1 |
| 47 | + } |
49 | 48 | } |
50 | | - return -1; |
| 49 | + return -1 |
51 | 50 | } |
52 | 51 | export { boyerMoore } |
0 commit comments