Last active
December 31, 2021 13:20
-
-
Save pomle/79e36db853df030b3eebf14fbb0865b7 to your computer and use it in GitHub Desktop.
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
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; | |
}; | |
}; | |
} |
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
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