From 0361fe5cf8e2dbb08461f4973152bb0c2e809fa7 Mon Sep 17 00:00:00 2001 From: Nicolas DUBIEN Date: Tue, 24 Jul 2018 11:26:22 +0200 Subject: [PATCH] Fix knuthMorrisPratt for empty word request (#101) --- .../knuth-morris-pratt/__test__/knuthMorrisPratt.test.js | 4 ++-- src/algorithms/string/knuth-morris-pratt/knuthMorrisPratt.js | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) 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;