From 8c70310f8ad6203012cd5eb5f39d90ac783671a5 Mon Sep 17 00:00:00 2001 From: Alok Date: Fri, 13 Oct 2023 18:53:02 +0530 Subject: [PATCH] updated the kmp from es5->es6 --- src/searching/knuth-morris-pratt.js | 65 ++++++++++++++--------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/src/searching/knuth-morris-pratt.js b/src/searching/knuth-morris-pratt.js index b4aeb85b..d395bd55 100644 --- a/src/searching/knuth-morris-pratt.js +++ b/src/searching/knuth-morris-pratt.js @@ -1,14 +1,17 @@ (function (exports) { 'use strict'; - var kmp = (function () { - function builtKMPTable(str) { - var res = []; - var len; - var front; - var end; - var found; - for (var i = 1; i <= str.length; i += 1) { + const kmp = (str, substr) => { + if (str === substr) { + return 0; + } + const builtKMPTable = (str) => { + const res = []; + let len; + let front; + let end; + let found; + for (let i = 1; i <= str.length; i += 1) { front = Math.max(1, i - ((res[i - 2] || 0) + 1)); end = Math.min(i - 1, (res[i - 2] || 0) + 1); found = false; @@ -25,7 +28,7 @@ res[i - 1] = len; } return res; - } + }; /** * Knuth–Morris–Pratt algorithm. Searches for the position of @@ -45,35 +48,29 @@ * where the specified substring occurs for the first * time, or -1 if it never occurs. */ - function indexOf(str, substr) { - if (str === substr) { - return 0; + + const table = builtKMPTable(substr); + let i = 0; + let j = 0; + while (i < str.length) { + if (str[i] === substr[j]) { + i += 1; + j += 1; } - var table = builtKMPTable(substr); - var i = 0; - var j = 0; - while (i < str.length) { - if (str[i] === substr[j]) { + if (j === substr.length) { + return i - j; + } + if (i < str.length && str[i] !== substr[j]) { + if (j > 0 && table[j - 1] !== 0) { + j = table[j - 1]; + } else { i += 1; - j += 1; - } - if (j === substr.length) { - return i - j; - } - if (i < str.length && str[i] !== substr[j]) { - if (j > 0 && table[j - 1] !== 0) { - j = table[j - 1]; - } else { - i += 1; - j = 0; - } + j = 0; } } - return -1; } - return indexOf; - }()); - + return -1; + }; exports.kmp = kmp; - })(typeof window === 'undefined' ? module.exports : window); +