File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash' ;
2+
3+ /**
4+ * @param {string } text - Text that may contain the searchable word.
5+ * @param {string } word - Word that is being searched in text.
6+ * @return {number } - Position of the word in text.
7+ */
8+ export default function rabinKarp ( text , word ) {
9+ const hasher = new PolynomialHash ( ) ;
10+
11+ // Calculate word hash that we will use for comparison with other substring hashes.
12+ const wordHash = hasher . hash ( word ) ;
13+
14+ let prevFrame = null ;
15+ let currentFrameHash = null ;
16+
17+ // Go through all substring of the text that may match.
18+ for ( let charIndex = 0 ; charIndex <= ( text . length - word . length ) ; charIndex += 1 ) {
19+ const currentFrame = text . substring ( charIndex , charIndex + word . length ) ;
20+
21+ // Calculate the hash of current substring.
22+ if ( currentFrameHash === null ) {
23+ currentFrameHash = hasher . hash ( currentFrame ) ;
24+ } else {
25+ currentFrameHash = hasher . roll ( currentFrameHash , prevFrame , currentFrame ) ;
26+ }
27+
28+ prevFrame = currentFrame ;
29+
30+ // Compare the hash of current substring and seeking string.
31+ // In case if hashes match let's make sure that substrings are equal.
32+ // In case of hash collision the strings may not be equal.
33+ if (
34+ wordHash === currentFrameHash
35+ && text . substr ( charIndex , word . length ) === word
36+ ) {
37+ return charIndex ;
38+ }
39+ }
40+
41+ return - 1 ;
42+ }
You can’t perform that action at this time.
0 commit comments