import { gcd } from "./fractions";

export function simplifyRatio(parts: number[]): number[] {
  if (parts.length === 0) return [];
  let g = parts[0];
  for (let i = 1; i < parts.length; i++) {
    g = gcd(g, parts[i]);
  }
  return parts.map((p) => p / g);
}

export function divideInRatio(total: number, parts: number[]): number[] {
  const sum = parts.reduce((a, b) => a + b, 0);
  const onePart = total / sum;
  return parts.map((p) => p * onePart);
}

export function ratioToFraction(a: number, b: number): [number, number] {
  return [a, a + b];
}

export function areEquivalent(ratio1: number[], ratio2: number[]): boolean {
  if (ratio1.length !== ratio2.length) return false;
  const s1 = simplifyRatio(ratio1);
  const s2 = simplifyRatio(ratio2);
  return s1.every((v, i) => v === s2[i]);
}

export function totalParts(parts: number[]): number {
  return parts.reduce((a, b) => a + b, 0);
}

export function ratioToKatex(parts: number[]): string {
  return parts.join(":");
}
