Skip to content

Instantly share code, notes, and snippets.

@alaindet
Created October 24, 2021 13:00
Show Gist options
  • Save alaindet/89e0fa22cb57eca8950643a509726f14 to your computer and use it in GitHub Desktop.
Save alaindet/89e0fa22cb57eca8950643a509726f14 to your computer and use it in GitHub Desktop.
Sorting helpers in TypeScript
type SortingFunction<T = any> = (a: T, b: T) => number;
/**
* Accepts a key, returns an ascending sorting function for that key
*/
const ascending = <T = any>(key: keyof T): SortingFunction<T> => {
return (a: any, b: any) => {
const aValue = a[key];
const bValue = b[key];
return (aValue === bValue) ? 0 : (aValue < bValue ? -1 : 1);
};
};
/**
* Accepts a key, returns a descending sorting function for that key
*/
const descending = <T = any>(key: keyof T): SortingFunction<T> => {
return (a: T, b: T) => {
const aValue = a[key];
const bValue = b[key];
return (aValue === bValue) ? 0 : (aValue > bValue ? -1 : 1);
};
};
// Try it out
const arr = [
{ foo: 22 },
{ foo: 11 },
{ foo: 33 },
];
console.log('Ascending');
console.log(arr.sort(ascending('foo')));
console.log('Descending');
console.log(arr.sort(descending('foo')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment