All files / src/utils statisticComparison.ts

100% Statements 22/22
100% Branches 10/10
100% Functions 1/1
100% Lines 22/22

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                                              1x 11x 11x 11x 11x 2x 2x   11x 3x 1x 2x 3x   6x 6x 2x 4x 4x 4x 4x 4x 4x 11x  
/**
 * Computes the percentage change between a current and baseline value.
 *
 * Rules:
 * - If either is null/undefined → no result.
 * - If both are 0 → no change.
 * - If baseline is 0 but current > 0 → 100% increase.
 * - If values are equal → no change.
 * - Otherwise → % difference from baseline.
 *
 * @param currentTotal - Current value.
 * @param baselineTotal - Baseline value.
 * @returns { isIncrease, changeNumber }
 *
 * @example
 * computeChange(120, 100) // { isIncrease: true, changeNumber: 20 }
 * computeChange(80, 100)  // { isIncrease: false, changeNumber: 20 }
 * computeChange(100, 100) // { isIncrease: undefined, changeNumber: 0 }
 * computeChange(0, 0)     // { isIncrease: undefined, changeNumber: 0 }
 * computeChange(50, 0)    // { isIncrease: true, changeNumber: 100 }
 */
type ChangeResult = { isIncrease: boolean; changeNumber: number };
 
export const computeChange = (
  currentTotal?: number,
  baselineTotal?: number | null,
): ChangeResult => {
  if (typeof currentTotal !== 'number' || typeof baselineTotal !== 'number') {
    return { isIncrease: false, changeNumber: 0 };
  }
 
  if (baselineTotal === 0) {
    return currentTotal === 0
      ? { isIncrease: false, changeNumber: 0 }
      : { isIncrease: currentTotal > 0, changeNumber: 100 };
  }
 
  const diff = currentTotal - baselineTotal;
  return diff === 0
    ? { isIncrease: false, changeNumber: 0 }
    : {
        isIncrease: diff > 0,
        changeNumber: Number(
          ((Math.abs(diff) / baselineTotal) * 100).toFixed(2),
        ),
      };
};