Utilities: Extract sorting function

Extracts the function used to sort packages as a utility function so it
can be reused for sorting locales as well.
This commit is contained in:
Lucas Garfield 2024-12-06 14:57:58 -06:00 committed by Lucas Garfield
parent 4899553151
commit 3d75b5b5ee
3 changed files with 36 additions and 71 deletions

29
src/Utilities/sortfn.ts Normal file
View file

@ -0,0 +1,29 @@
const sortfn = (a: string, b: string, searchTerm: string) => {
const x = a.toLowerCase();
const y = b.toLowerCase();
// check exact match first
if (x === searchTerm) {
return -1;
}
if (y === searchTerm) {
return 1;
}
// check for packages that start with the search term
if (x.startsWith(searchTerm) && !y.startsWith(searchTerm)) {
return -1;
}
if (y.startsWith(searchTerm) && !x.startsWith(searchTerm)) {
return 1;
}
// if both (or neither) start with the search term
// sort alphabetically
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
};
export default sortfn;