SplitEquallyState.calculate constructor

SplitEquallyState.calculate({
  1. required Decimal outstandingAmount,
  2. required int numberOfCustomers,
})

Creates a new SplitEquallyState from the outstanding amount and desired number of customers.

Uses integer-cent arithmetic to avoid floating-point errors:

  • baseShareCents = totalCents ~/ numberOfCustomers
  • lastShareCents = baseShareCents + (totalCents - baseShareCents * numberOfCustomers)

Implementation

factory SplitEquallyState.calculate({
  required Decimal outstandingAmount,
  required int numberOfCustomers,
}) {
  final totalCents =
      (outstandingAmount * Decimal.fromInt(100)).truncate().toBigInt().toInt();
  final base = totalCents ~/ numberOfCustomers;
  final remainder = totalCents - (base * numberOfCustomers);
  return SplitEquallyState(
    numberOfCustomers: numberOfCustomers,
    totalCents: totalCents,
    baseShareCents: base,
    lastShareCents: base + remainder,
    customersServed: 0,
  );
}