Created
September 16, 2020 08:08
-
-
Save MikelArnaiz/4a46902889f00982358022bd2fa2020a to your computer and use it in GitHub Desktop.
Sort compare function with key accessor
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 FilteredKeys<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T] | |
const compare = <T>(fn: (x: T, y: T) => number) => <O extends object>(key: FilteredKeys<O, T>) => ( | |
a: O, | |
b: O, | |
): number => { | |
const valA = (a[key] as unknown) as T | |
const valB = (b[key] as unknown) as T | |
return fn(valA, valB) | |
} | |
export const compareStrings = compare<string>((a, b) => a.localeCompare(b)) | |
export const compareDates = compare<Date>((a, b) => a.valueOf() - b.valueOf() ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment