export function allocatePercentages(weights: number[], decimals = 1) {
  const safeWeights = weights.map((weight) => Math.max(0, Number(weight) || 0));
  const total = safeWeights.reduce((sum, weight) => sum + weight, 0);
  if (!total) return safeWeights.map(() => null);

  const scale = 10 ** decimals;
  const targetUnits = 100 * scale;
  const rawUnits = safeWeights.map((weight) => (weight / total) * targetUnits);
  const allocated = rawUnits.map(Math.floor);
  let remainder = targetUnits - allocated.reduce((sum, value) => sum + value, 0);
  const order = rawUnits
    .map((value, index) => ({ index, fraction: value - allocated[index] }))
    .sort((left, right) => right.fraction - left.fraction || left.index - right.index);

  for (let index = 0; remainder > 0; index += 1, remainder -= 1) {
    allocated[order[index % order.length].index] += 1;
  }
  return allocated.map((value) => value / scale);
}
