Skip to content

Instantly share code, notes, and snippets.

@Graniron
Created June 3, 2021 13:34
Show Gist options
  • Save Graniron/20b4552ea7be8b5f16164789de8ff158 to your computer and use it in GitHub Desktop.
Save Graniron/20b4552ea7be8b5f16164789de8ff158 to your computer and use it in GitHub Desktop.
Arrays utils
<!-- 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