Created
June 3, 2021 13:34
-
-
Save Graniron/20b4552ea7be8b5f16164789de8ff158 to your computer and use it in GitHub Desktop.
Arrays utils
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
<!-- Helpers --> | |
const isFiniteNumber = (n: any): n is number => Number.isFinite(n); | |
const isString = (s: any): s is string => s === '' || (s && typeof s.valueOf() === 'string'); | |
const matchId = (valueToMatch: string) => (item: { id: string }) => valueToMatch === item.id; | |
const sortBy = <T>(valueGetterFn: (item: T) => number | string, direction: 'asc' | 'desc') => (itemA: T, itemB: T): number => { | |
const a = valueGetterFn(itemA); | |
const b = valueGetterFn(itemB); | |
if (isFiniteNumber(a) && isFiniteNumber(b)) { | |
return direction === 'asc' ? a - b : b - a; | |
} else if (isString(a) && isString(b)) { | |
return direction === 'asc' ? (a < b ? -1 : 1) : a < b ? 1 : -1; | |
} | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment