JSFiddle - React, Tailwind, and code Playground
by Qwerty_Wasd
JavaScript
let opRK = {
getHash: (text, pPow, r) => {
let hash = 0;
for(let i = 0; i < text.length; i++) hash += (pPow[text.length - 1 - i] * text[i].charCodeAt(0)) % r;
return hash;
},
getMatches: (string, subString) => {
let opTmp = {
collisions: 0,
r: 101,
entries: [],
pPow: [1],
substringtext:string.substring(0,subString.length),
};
for (let i = 1; i <= subString.length; i++) opTmp.pPow.push(opTmp.pPow[i - 1] * 2);
opTmp.stringHash = opRK.getHash(opTmp.substringtext, opTmp.pPow, opTmp.r);
opTmp.subStringHash = opRK.getHash(subString, opTmp.pPow, opTmp.r);
for (let i = 0; i < string.length - subString.length; i++) {
if (opTmp.subStringHash !== opTmp.stringHash) {
(opTmp.substringtext === subString) ? opTmp.entries.push(i - 1) : opTmp.collisions++;
opTmp.substringtext = string.substring(i, i + subString.length);
}
opTmp.stringHash = (((2 * ((opTmp.stringHash - (string[i].charCodeAt(0) * opTmp.pPow[subString.length - 1] % opTmp.r)) % opTmp.r) % opTmp.r) + string[i + subString.length].charCodeAt(0)) % opTmp.r);
}
return [opTmp.entries, opTmp.collisions, opTmp.entries.length];
}
};
console.log(opRK.getMatches(`abbbbaaaaaaaaaaaa adsas`, `a`));