Created
March 29, 2021 06:19
-
-
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).
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
/* 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