Skip to content

Instantly share code, notes, and snippets.

@pomle
Last active December 31, 2021 13:20
Show Gist options
  • Save pomle/79e36db853df030b3eebf14fbb0865b7 to your computer and use it in GitHub Desktop.
Save pomle/79e36db853df030b3eebf14fbb0865b7 to your computer and use it in GitHub Desktop.
type Direction = "asc" | "desc";
export function sortBy<T>(val: (value: T) => number) {
return function sort(dir: Direction) {
const invert = dir === "asc" ? 1 : -1;
return function compare(a: T, b: T) {
return (val(a) - val(b)) * invert;
};
};
}
import { sortBy } from "./sort";
class MyObject {
created: Date = new Date();
}
const byCreated = sortBy<MyObject>((o) => o.created.valueOf());
const myObjects = [
new MyObject(),
new MyObject(),
new MyObject(),
];
myObjects.sort(byCreated("asc"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment