Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TypeScript comparator factory for Array.sort()
// 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
You can’t perform that action at this time.