Skip to content

Instantly share code, notes, and snippets.

@kbrsh
Last active May 21, 2017 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbrsh/9dc89ee1ecbbe99a631f989dab09b25c to your computer and use it in GitHub Desktop.
Save kbrsh/9dc89ee1ecbbe99a631f989dab09b25c to your computer and use it in GitHub Desktop.
Search Algorithms
const createTable = function(item, length) {
let table = new Array(length);
table[0] = 0;
for(let i = 1; i < length; i++) {
var section = item.substring(0, i + 1);
var sectionLength = section.length;
var val = 0;
for(let j = sectionLength - 1; j > 0; j--) {
const prefix = section.substring(0, j);
const suffix = section.slice(-j);
if(prefix === suffix) {
val = prefix.length;
break;
}
}
table[i] = val;
}
return table;
}
const search = function(item, str) {
const m = item.length;
const n = str.length;
const searchable = n - m + 1;
const table = createTable(item, m);
let match = false;
for(let i = 0; i < searchable; i++) {
let partial = "";
for(let j = 0; j < m; j++) {
const char = item[j];
if(char === str[i + j]) {
match = true;
partial += char;
} else {
match = false;
break;
}
}
const partialLength = partial.length;
let tableValue = undefined;
let skip = 0;
if(match === true) {
break;
} else if(partialLength !== 0 && (tableValue = table[partialLength - 1]) > 0 && (skip = partialLength - table[partialLength - 1]) > 0) {
i += skip;
}
}
return match;
}
const search = function(item, str) {
const m = item.length;
const n = str.length;
const searchable = n - m + 1;
let match = false;
for(let i = 0; i < searchable; i++) {
for(let j = 0; j < m; j++) {
if(item[j] === str[i + j]) {
match = true;
} else {
match = false;
break;
}
}
if(match === true) {
break;
}
}
return match;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment