Created
October 24, 2021 13:00
-
-
Save alaindet/89e0fa22cb57eca8950643a509726f14 to your computer and use it in GitHub Desktop.
Sorting helpers in TypeScript
This file contains 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 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