mirror of
https://github.com/mipmip/home-manager-option-search.git
synced 2024-09-11 15:16:31 +03:00
sort resuts based on term appearance in results
This commit is contained in:
parent
3ff0382a99
commit
f97949ad14
43
js/script.js
43
js/script.js
@ -137,6 +137,49 @@ var setSearchQueryToUrlParam = function(query) {
|
||||
|
||||
var searchOptions = function(query) {
|
||||
results = search.search(query);
|
||||
|
||||
// Performance optimization: skip ordering if query is a single character
|
||||
if (query.length > 1) {
|
||||
// Split terms by non-alphanumeric chars
|
||||
const terms = query.split(/[^A-Za-z0-9]/);
|
||||
|
||||
results.sort((a, b) => {
|
||||
// Concatenate to sort first by occurence in title, then description.
|
||||
const aConcat = a.title + a.description;
|
||||
const bConcat = b.title + b.description;
|
||||
|
||||
// We store last found index, to order based on remaining string.
|
||||
// This assumes that terms are written in the order that the user
|
||||
// expects them to appear in the title + description.
|
||||
var lastIndex = 0;
|
||||
|
||||
for (var i = 0; i < terms.length; i++) {
|
||||
const term = terms[i];
|
||||
const aIndex = aConcat.slice(lastIndex).indexOf(term);
|
||||
|
||||
// Not found in a, b must come first
|
||||
if (aIndex == -1) return 1;
|
||||
|
||||
// No reason to index beyond result of lastIndex +aIndex + term.length,
|
||||
// as a would come first in that case.
|
||||
const bIndex = bConcat
|
||||
.slice(lastIndex, lastIndex + aIndex + term.length)
|
||||
.indexOf(term);
|
||||
|
||||
// Not found in b, a must come first
|
||||
if (bIndex == -1) return -1;
|
||||
if (aIndex !== bIndex) return aIndex - bIndex
|
||||
|
||||
// Increment lastIndex by found index and term length, to sort based
|
||||
// on remaining string.
|
||||
lastIndex += aIndex + term.length;
|
||||
}
|
||||
|
||||
// Default to alphabetical order otherwise
|
||||
return aConcat.localeCompare(bConcat);
|
||||
});
|
||||
}
|
||||
|
||||
updateOptionCountAndTable();
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user