Skip to content

Instantly share code, notes, and snippets.

@theredhead
Created March 29, 2021 06:19
Show Gist options
  • Save theredhead/f71d8d19209409e07cd2ff39a3cd9242 to your computer and use it in GitHub Desktop.
Save theredhead/f71d8d19209409e07cd2ff39a3cd9242 to your computer and use it in GitHub Desktop.
Typescript generic "make a compare function" function that takes a lambda, expected to return the property to compare (normally).
/* Create a function used with `sort()` to sort arrays of objects
* for example:
* const sortByLastName = makeCompareFunction<Person>(p => p.lastName);
* people.sort(sortByLastName);
*/
export function makeCompareFunction<T>(lambda: (obj: T) => string | number) {
return (a: T, b: T): number => {
const _a = lambda(a);
const _b = lambda(b);
if (_a < _b) {
return -1;
}
if (_a > _b) {
return 1;
}
return 0;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment