@zerospacegg/vynthra
Version:
Discord bot for ZeroSpace.gg data
62 lines (55 loc) • 1.6 kB
text/typescript
// Fuzzy string matching utilities using fuzzy
import fuzzy from "fuzzy";
/**
* Create a fuzzy matcher for a collection of strings
*/
export function createFuzzyMatcher<T>(
items: T[],
selector: (item: T) => string,
): { items: T[]; selector: (item: T) => string } {
return { items, selector };
}
/**
* Fuzzy search items with a query string
*/
export function fuzzySearch<T>(
matcher: { items: T[]; selector: (item: T) => string },
query: string,
limit: number = 10,
): Array<{ item: T; score: number; positions: Set<number> }> {
const results = fuzzy.filter(query, matcher.items, {
extract: matcher.selector,
});
return results.slice(0, limit).map((result) => ({
item: result.original,
score: result.score,
positions: new Set<number>(), // fuzzy package doesn't provide positions
}));
}
/**
* Check if a string contains another string (case insensitive)
*/
export function contains(query: string, target: string): boolean {
if (query == null || target == null) {
return false;
}
return target.toLowerCase().includes(query.toLowerCase());
}
/**
* Check if target starts with query (case insensitive)
*/
export function startsWith(query: string, target: string): boolean {
if (query == null || target == null) {
return false;
}
return target.toLowerCase().startsWith(query.toLowerCase());
}
/**
* Exact match check (case insensitive)
*/
export function exactMatch(query: string, target: string): boolean {
if (query == null || target == null) {
return false;
}
return query.toLowerCase() === target.toLowerCase();
}