Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions packages/ts-utils/src/sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Maps an element of an array to a number and returns a function
* that compares the number value of two values.
*
* Call this and pass the result into the .sort function.
*
* The array gets sorted in such a way that the elements get sorted
* by the number they map to.
*
* So the higher the number, the later in the array the element will be.
*
* If the number is same, the order is kept the same (.sort uses a stable sorting algorithm)
*
* Especially useful when you need
* - to push some items to the front (for example user's favorite item)
* - other items to the back (for example inactive items)
* - keep the order of the other items the same
*
* @example
* ```
* const arr = ['alpha', 'beta', 'gamma']
*
* const userFavoriteGreekLetter = 'gamma'
*
* // we want to push the favorite greek letter to the front
* arr.sort(numberComparator(x => x === userFavoriteGreekLetter ? -1 : 0))
*
* // prints "gamma, alpha, beta"
* console.log(arr.join(', '))
* ```
*/
export function numberComparator<T>(
map: (x: T) => number
): (p: T, n: T) => number {
return (p: T, n: T): number => {
const pNumber = map(p);
const nNumber = map(n);

return pNumber - nNumber;
};
}
Loading