Skip to content

Instantly share code, notes, and snippets.

@bennidhamma
Last active May 30, 2021 00:53
Show Gist options
  • Save bennidhamma/5b20c2b40cefcaaf422e9f80d810af4a to your computer and use it in GitHub Desktop.
Save bennidhamma/5b20c2b40cefcaaf422e9f80d810af4a to your computer and use it in GitHub Desktop.
This is a type safe replacement for lodash _.orderBy
// use like:
items.sort(orderBy<WorkGroup>([x => x.priorityScore, x => x.sortTime], ['desc', 'asc']);
type Sortable = number | Date | string;
type Direction = "asc" | "desc";
type SortPredicate<T> = (x: T) => Sortable;
export function orderBy<T>(
predicates: SortPredicate<T>[] = [],
directions: Direction[] = []
) {
if (predicates.length === 0) {
predicates = [(x) => (x as unknown) as Sortable];
}
const sort = (
a: T,
b: T,
p: SortPredicate<T>,
ps: SortPredicate<T>[],
direction: Direction,
ds: Direction[]
): number => {
const dir =
direction === "asc"
? (x: Sortable, y: Sortable) => x > y
: (x: Sortable, y: Sortable) => x < y;
if (!p) {
return 0;
}
if (dir(p(a), p(b))) {
return 1;
}
if (dir(p(b), p(a))) {
return -1;
}
return sort(a, b, ps[0], ps.slice(1), ds[0], ds.slice(1));
};
return (a: T, b: T) =>
sort(
a,
b,
predicates[0],
predicates.slice(1),
directions[0],
directions.slice(1)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment