All files / src/components/table sort.ts

56.75% Statements 21/37
61.9% Branches 26/42
33.33% Functions 3/9
61.76% Lines 21/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81    5x 5x 3x 1x   2x         2x 2x     2x       2x       2x       2x 1x   1x       1x       6x     6x         5x 5x   5x 3x     2x                                                    
export function descendingComparator<T>(a: T, b: T, orderBy: keyof T, order: SortOrder): number {
  // first attempt to parse into a numeric value and compare
  const numCompare = descendingNumComparator(a, b, orderBy);
  if (numCompare !== null) {
    if (numCompare === 0) {
      return numCompare;
    } else {
      return order === 'desc' ? numCompare * -1 : numCompare;
    }
  }
 
  // if non-numeric, compare using the javascript built-in compare for this type
  const bValue = b[orderBy] ?? '';
  const aValue = a[orderBy] ?? '';
 
  // blank values at the end always (any order)
  Iif (isEmptyValue(aValue.toString()) && isEmptyValue(bValue.toString())) {
    return 0;
  }
 
  Iif (isEmptyValue(aValue.toString())) {
    return 1;
  }
 
  Iif (isEmptyValue(bValue.toString())) {
    return -1;
  }
 
  if (bValue < aValue) {
    return order === 'desc' ? -1 : 1;
  }
  Iif (bValue > aValue) {
    return order === 'desc' ? 1 : -1;
  }
 
  return 0;
}
 
function isEmptyValue(value?: string): boolean {
  Iif (value === '' || value === null || value?.toString().trim() === '' || value === undefined) {
    return true;
  } else {
    return false;
  }
}
 
function descendingNumComparator<T>(a: T, b: T, orderBy: keyof T): number | null {
  const aNumValue = Number((a[orderBy] ?? '0.0') as string);
  const bNumValue = Number((b[orderBy] ?? '0.0') as string);
 
  if (!isNaN(aNumValue) && !isNaN(bNumValue)) {
    return bNumValue - aNumValue;
  }
 
  return null;
}
 
export type SortOrder = 'asc' | 'desc';
 
export function getComparator<Key extends keyof any>(
  order: SortOrder,
  orderBy: Key,
  sorting: (a: any, b: any, orderBy: any, order: SortOrder) => number
): (a: { [key in Key]?: string | number | [] }, b: { [key in Key]?: string | number | [] }) => number {
  return (a, b) => sorting(a, b, orderBy, order);
}
 
export function stableSort<T>(array: T[], comparator: (a: T, b: T) => number): T[] {
  const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) {
      return order;
    }
 
    return a[1] - b[1];
  });
 
  return stabilizedThis.map((el) => el[0]);
}