All files / components/hooks/gapChart useGapChartData.ts

0% Statements 0/26
0% Branches 0/8
0% Functions 0/11
0% Lines 0/19

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                                                                                                                                             
import { useMemo } from "react";
 
interface DataItem {
  label: string;
  code?: string;
  value1: number;
  value2: number;
  difference: number;
  date: string;
}
 
interface Filter {
  limit: number;
  date: number | string;
  criteria: string;
  sortingDir: "asc" | "desc";
}
 
export const useGapChartData = (
  dataSet: DataItem[],
  filter: Filter | undefined,
  disabledItems: string[]
) => {
  // Calculate differences and filter data
  const processedDataSet = useMemo(() => {
    const dataWithDifference = dataSet.map(item => ({
      ...item,
      difference: item.value1 - item.value2,
    }));
 
    if (!filter) {
      return dataWithDifference.filter(d => !disabledItems.includes(d.label));
    }
 
    // Filter by date if specified
    const dateFilteredData = filter.date
      ? dataWithDifference.filter(d => d.date === filter.date)
      : dataWithDifference;
 
    // Sort by difference
    const sortedData = dateFilteredData.slice().sort((a, b) => {
      const diff =
        filter.sortingDir === "desc" ? b.difference - a.difference : a.difference - b.difference;
      return diff;
    });
 
    // Apply limit and remove disabled items
    return sortedData.slice(0, filter.limit).filter(d => !disabledItems.includes(d.label));
  }, [dataSet, filter, disabledItems]);
 
  // Get unique labels for y-axis
  const yAxisDomain = useMemo(() => processedDataSet.map(d => d.label), [processedDataSet]);
 
  // Calculate x-axis domain (min and max values)
  const xAxisDomain = useMemo((): [number, number] => {
    if (processedDataSet.length === 0) return [0, 0];
 
    const allValues = processedDataSet.flatMap(d => [d.value1, d.value2]);
    const min = Math.min(...allValues, 0);
    const max = Math.max(...allValues);
 
    return [min, max];
  }, [processedDataSet]);
 
  return {
    processedDataSet,
    yAxisDomain,
    xAxisDomain,
  };
};