// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {if (pattern.length == 0)return 0; // Immediate match
// Compute longest suffix-prefix tablevar lsp = [0]; // Base casefor (var i = 1; i < pattern.length; i++) {var j = lsp[i - 1]; // Start by assuming we're extending the previous LSPwhile (j > 0 && pattern[i] !== pattern[j])j = lsp[j - 1];if (pattern[i] === pattern[j])j++;lsp.push(j);}
// Walk through text stringvar j = 0; // Number of chars matched in patternfor (var i = 0; i < text.length; i++) {while (j > 0 && text[i] != pattern[j])j = lsp[j - 1]; // Fall back in the patternif (text[i] == pattern[j]) {j++; // Next char matched, increment positionif (j == pattern.length)return i - (j - 1);}}return -1; // Not found}
console.log(kmpSearch('ays', 'haystack') != -1) // trueconsole.log(kmpSearch('asdf', 'haystack') != -1) // false