Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix linter
  • Loading branch information
midzer committed Feb 26, 2025
commit 7b0afe9ce945ed91d8c73e0df345a942f7a478b5
38 changes: 25 additions & 13 deletions src/scripts/search/kmp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,43 @@ import { Options } from '../interfaces';
import { Searcher, SearchResult } from '../interfaces/search';

function kmpSearch(pattern: string, text: string): number {
if (pattern.length == 0) return 0; // Immediate match
if (pattern.length === 0) {
return 0; // Immediate match
}

// Compute longest suffix-prefix table
var lsp = [0]; // Base case
for (var i = 1; i < pattern.length; i++) {
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) != pattern.charAt(j)) j = lsp[j - 1];
if (pattern.charAt(i) == pattern.charAt(j)) j++;
const lsp = [0]; // Base case
for (let i = 1; i < pattern.length; i++) {
let j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) !== pattern.charAt(j)) {
j = lsp[j - 1];
}
if (pattern.charAt(i) === pattern.charAt(j)) {
j++;
}
lsp.push(j);
}

// Walk through text string
var j = 0; // Number of chars matched in pattern
for (var i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j)) j = lsp[j - 1]; // Fall back in the pattern
if (text.charAt(i) == pattern.charAt(j)) {
let j = 0; // Number of chars matched in pattern
for (let i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) !== pattern.charAt(j)) {
j = lsp[j - 1]; // Fall back in the pattern
}
if (text.charAt(i) === pattern.charAt(j)) {
j++; // Next char matched, increment position
if (j == pattern.length) return i - (j - 1);
if (j === pattern.length) {
return i - (j - 1);
}
}
}

return -1; // Not found
}

export class SearchByKMP<T extends object> implements Searcher<T> {
_fields: string[];

_limit: number;

_haystack: T[] = [];
Expand Down Expand Up @@ -62,11 +74,11 @@ export class SearchByKMP<T extends object> implements Searcher<T> {
const obj = this._haystack[i];
for (let k = 0, l = this._fields.length; k < l; k++) {
const field = this._fields[k];
if (field in obj && kmpSearch(needle, (obj[field] as string).toLowerCase()) != -1) {
if (field in obj && kmpSearch(needle, (obj[field] as string).toLowerCase()) !== -1) {
results.push({
item: obj[field],
score: count,
rank: count + 1
rank: count + 1,
});
if (++count === this._limit) {
break;
Expand Down