All files / src/utilities vbc-utils.ts

100% Statements 21/21
100% Branches 10/10
100% Functions 3/3
100% Lines 18/18

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 3436x 171x 17x   154x 413x   154x 154x   406x     406x     154x     154x     36x 168x 168x 16x   304x     152x 152x    
export const getClosestPairDiffAndRange = (data: number[] | Date[]): [number, number] | undefined => {
  if (data.length < 2) {
    return;
  }
  data = data.sort((a, b) =>
    a instanceof Date ? (a as Date).getTime() - (b as Date).getTime() : (a as number) - (b as number),
  );
  let minDiff = Number.MAX_VALUE;
  for (let i = 1; i < data.length; i++) {
    const diff =
      data[i] instanceof Date
        ? (data[i] as Date).getTime() - (data[i - 1] as Date).getTime()
        : (data[i] as number) - (data[i - 1] as number);
    minDiff = Math.min(minDiff, diff);
  }
  const range =
    data[0] instanceof Date
      ? (data[data.length - 1] as Date).getTime() - (data[0] as Date).getTime()
      : (data[data.length - 1] as number) - (data[0] as number);
  return [minDiff, range];
};
 
export const calculateAppropriateBarWidth = (data: number[] | Date[], totalWidth: number) => {
  const result = getClosestPairDiffAndRange(data);
  if (!result || result[1] === 0) {
    return 16;
  }
  const [closestPairDiff, range] = result;
  // Refer to https://microsoft.github.io/fluentui-charting-contrib/docs/rfcs/fix-overlapping-bars-on-continuous-axes
  // for the derivation of the following formula.
  const barWidth = Math.round((totalWidth * closestPairDiff) / (2 * range + closestPairDiff));
  return barWidth;
};