From a84ae25478e2fa7b5449c5a68dfe13827beec017 Mon Sep 17 00:00:00 2001 From: Matej Smid Date: Thu, 12 Jun 2025 13:07:24 +0200 Subject: [PATCH] f/matej-utils - add: numberComparator --- packages/ts-utils/src/sort.ts | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 packages/ts-utils/src/sort.ts diff --git a/packages/ts-utils/src/sort.ts b/packages/ts-utils/src/sort.ts new file mode 100644 index 0000000..1b2c387 --- /dev/null +++ b/packages/ts-utils/src/sort.ts @@ -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( + 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; + }; +}