MCPcopy
hub / github.com/mgechev/javascript-algorithms / indexOf

Function indexOf

src/searching/knuth-morris-pratt.js:48–73  ·  view source on GitHub ↗

* 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)

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 1

builtKMPTableFunction · 0.85

Tested by

no test coverage detected