Tweak relevant sort algorithm (#4902)

* Remove multi-space before getting words
* Trim names and aliases
This commit is contained in:
WithoutPants 2024-05-31 17:50:05 +10:00 committed by GitHub
parent 3b146588c6
commit eec31723bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -36,9 +36,9 @@ export function sortByRelevance<T extends ISortable>(
const cache: Record<string, ICacheEntry> = {}; const cache: Record<string, ICacheEntry> = {};
function setCache(tag: T, partial: Partial<ICacheEntry>) { function setCache(o: T, partial: Partial<ICacheEntry>) {
cache[tag.id] = { cache[o.id] = {
...cache[tag.id], ...cache[o.id],
...partial, ...partial,
}; };
} }
@ -54,7 +54,7 @@ export function sortByRelevance<T extends ISortable>(
return []; return [];
} }
const aliases = getAliases(o)?.map((a) => a.toLowerCase()) ?? []; const aliases = getAliases(o)?.map((a) => a.trim().toLowerCase()) ?? [];
setCache(o, { aliases }); setCache(o, { aliases });
return aliases; return aliases;
@ -88,13 +88,18 @@ export function sortByRelevance<T extends ISortable>(
return startsWith; return startsWith;
} }
function getWords(o: T) { function getWords(n: string) {
return getName(o).trim().toLowerCase().split(" "); // trim and remove any extra spaces
return n.trim().replace(/\s\s+/g, " ").toLowerCase().split(" ");
} }
function getAliasWords(tag: T) { function getNameWords(o: T) {
const aliases = getObjectAliases(tag); return getWords(getName(o));
return aliases.map((a) => a.trim().split(" ")).flat(); }
function getAliasWords(o: T) {
const aliases = getObjectAliases(o);
return aliases.map((a) => getWords(a)).flat();
} }
function getWordIndex(o: T) { function getWordIndex(o: T) {
@ -104,7 +109,7 @@ export function sortByRelevance<T extends ISortable>(
return cached; return cached;
} }
const words = getWords(o); const words = getNameWords(o);
const wordIndex = words.findIndex((w) => w === query); const wordIndex = words.findIndex((w) => w === query);
setCache(o, { wordIndex }); setCache(o, { wordIndex });
@ -132,7 +137,7 @@ export function sortByRelevance<T extends ISortable>(
return cached; return cached;
} }
const words = getWords(o); const words = getNameWords(o);
const wordStartsWithIndex = words.findIndex((w) => w.startsWith(query)); const wordStartsWithIndex = words.findIndex((w) => w.startsWith(query));
setCache(o, { wordStartsWithIndex }); setCache(o, { wordStartsWithIndex });
@ -170,8 +175,8 @@ export function sortByRelevance<T extends ISortable>(
} }
function compare(a: T, b: T) { function compare(a: T, b: T) {
const aName = getName(a).toLowerCase(); const aName = getName(a).trim().toLowerCase();
const bName = getName(b).toLowerCase(); const bName = getName(b).trim().toLowerCase();
const aAlias = aliasMatches(a); const aAlias = aliasMatches(a);
const bAlias = aliasMatches(b); const bAlias = aliasMatches(b);