* Knuth–Morris–Pratt algorithm. Searches for the position of * the first occurrence of a specified value in a string. * * @example * * var indexOf = require('path-to-algorithm/src/searching/'+ * 'knuth-morris-pratt').kmp; * console.log(indexOf('hello', 'll')); // 2
(str, substr)
| 46 | * time, or -1 if it never occurs. |
| 47 | */ |
| 48 | function indexOf(str, substr) { |
| 49 | if (str === substr) { |
| 50 | return 0; |
| 51 | } |
| 52 | var table = builtKMPTable(substr); |
| 53 | var i = 0; |
| 54 | var j = 0; |
| 55 | while (i < str.length) { |
| 56 | if (str[i] === substr[j]) { |
| 57 | i += 1; |
| 58 | j += 1; |
| 59 | } |
| 60 | if (j === substr.length) { |
| 61 | return i - j; |
| 62 | } |
| 63 | if (i < str.length && str[i] !== substr[j]) { |
| 64 | if (j > 0 && table[j - 1] !== 0) { |
| 65 | j = table[j - 1]; |
| 66 | } else { |
| 67 | i += 1; |
| 68 | j = 0; |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | return -1; |
| 73 | } |
| 74 | return indexOf; |
| 75 | }()); |
| 76 |
no test coverage detected