diff --git a/src/algorithms/string/knuth-morris-pratt/__test__/knuthMorrisPratt.test.js b/src/algorithms/string/knuth-morris-pratt/__test__/knuthMorrisPratt.test.js index 42e6f81c..17f6a696 100644 --- a/src/algorithms/string/knuth-morris-pratt/__test__/knuthMorrisPratt.test.js +++ b/src/algorithms/string/knuth-morris-pratt/__test__/knuthMorrisPratt.test.js @@ -2,8 +2,8 @@ import knuthMorrisPratt from '../knuthMorrisPratt'; describe('knuthMorrisPratt', () => { it('should find word position in given text', () => { - expect(knuthMorrisPratt('', '')).toBe(-1); - expect(knuthMorrisPratt('a', '')).toBe(-1); + expect(knuthMorrisPratt('', '')).toBe(0); + expect(knuthMorrisPratt('a', '')).toBe(0); expect(knuthMorrisPratt('a', 'a')).toBe(0); expect(knuthMorrisPratt('abcbcglx', 'abca')).toBe(-1); expect(knuthMorrisPratt('abcbcglx', 'bcgl')).toBe(3); diff --git a/src/algorithms/string/knuth-morris-pratt/knuthMorrisPratt.js b/src/algorithms/string/knuth-morris-pratt/knuthMorrisPratt.js index 4c008e44..e4344b77 100644 --- a/src/algorithms/string/knuth-morris-pratt/knuthMorrisPratt.js +++ b/src/algorithms/string/knuth-morris-pratt/knuthMorrisPratt.js @@ -30,6 +30,10 @@ function buildPatternTable(word) { * @return {number} */ export default function knuthMorrisPratt(text, word) { + if (word.length === 0) { + return 0; + } + let textIndex = 0; let wordIndex = 0;