|
| 1 | +import { Options } from '../interfaces'; |
| 2 | +import { Searcher, SearchResult } from '../interfaces/search'; |
| 3 | + |
| 4 | +function kmpSearch(pattern: string, text: string): number { |
| 5 | + if (pattern.length === 0) { |
| 6 | + return 0; // Immediate match |
| 7 | + } |
| 8 | + |
| 9 | + // Compute longest suffix-prefix table |
| 10 | + const lsp = [0]; // Base case |
| 11 | + for (let i = 1; i < pattern.length; i++) { |
| 12 | + let j = lsp[i - 1]; // Start by assuming we're extending the previous LSP |
| 13 | + while (j > 0 && pattern.charAt(i) !== pattern.charAt(j)) { |
| 14 | + j = lsp[j - 1]; |
| 15 | + } |
| 16 | + if (pattern.charAt(i) === pattern.charAt(j)) { |
| 17 | + j++; |
| 18 | + } |
| 19 | + lsp.push(j); |
| 20 | + } |
| 21 | + |
| 22 | + // Walk through text string |
| 23 | + let j = 0; // Number of chars matched in pattern |
| 24 | + for (let i = 0; i < text.length; i++) { |
| 25 | + while (j > 0 && text.charAt(i) !== pattern.charAt(j)) { |
| 26 | + j = lsp[j - 1]; // Fall back in the pattern |
| 27 | + } |
| 28 | + if (text.charAt(i) === pattern.charAt(j)) { |
| 29 | + j++; // Next char matched, increment position |
| 30 | + if (j === pattern.length) { |
| 31 | + return i - (j - 1); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return -1; // Not found |
| 37 | +} |
| 38 | + |
| 39 | +export class SearchByKMP<T extends object> implements Searcher<T> { |
| 40 | + _fields: string[]; |
| 41 | + |
| 42 | + _haystack: T[] = []; |
| 43 | + |
| 44 | + constructor(config: Options) { |
| 45 | + this._fields = config.searchFields; |
| 46 | + } |
| 47 | + |
| 48 | + index(data: T[]): void { |
| 49 | + this._haystack = data; |
| 50 | + } |
| 51 | + |
| 52 | + reset(): void { |
| 53 | + this._haystack = []; |
| 54 | + } |
| 55 | + |
| 56 | + isEmptyIndex(): boolean { |
| 57 | + return !this._haystack.length; |
| 58 | + } |
| 59 | + |
| 60 | + search(_needle: string): SearchResult<T>[] { |
| 61 | + const fields = this._fields; |
| 62 | + if (!fields || !fields.length || !_needle) { |
| 63 | + return []; |
| 64 | + } |
| 65 | + const needle = _needle.toLowerCase(); |
| 66 | + |
| 67 | + const results: SearchResult<T>[] = []; |
| 68 | + |
| 69 | + let count = 0; |
| 70 | + for (let i = 0, j = this._haystack.length; i < j; i++) { |
| 71 | + const obj = this._haystack[i]; |
| 72 | + for (let k = 0, l = this._fields.length; k < l; k++) { |
| 73 | + const field = this._fields[k]; |
| 74 | + if (field in obj && kmpSearch(needle, (obj[field] as string).toLowerCase()) !== -1) { |
| 75 | + results.push({ |
| 76 | + item: obj[field], |
| 77 | + score: count, |
| 78 | + rank: count + 1, |
| 79 | + }); |
| 80 | + count++; |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return results; |
| 86 | + } |
| 87 | +} |
0 commit comments