Created
May 29, 2019 22:37
-
-
Save langpavel/335e7f956f7a08828988ba821ce31bf9 to your computer and use it in GitHub Desktop.
TypeScript comparator factory for Array.sort()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
const candidates: any[] = []; | |
// ... | |
candidates.sort(createComparator( | |
(x) => x.ambiguous, | |
(_, y) => y.refCount, // DESC | |
(x) => x.name.length, | |
(x) => x.name, | |
)); | |
// Source | |
type ComparatorSelector<T> = (value: T, other: T) => number | string | null; | |
export function createComparator<T>(...selectors: ComparatorSelector<T>[]) { | |
return (a: T, b: T) => { | |
for (const selector of selectors) { | |
const valA = selector(a, b); | |
if (valA === null) continue; | |
const valB = selector(b, a); | |
if (valB === null || valA == valB) continue; | |
if (valA > valB) return 1; | |
if (valA < valB) return -1; | |
} | |
return 0; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment