MixedFraction constructor

MixedFraction({
  1. required int whole,
  2. required int numerator,
  3. required int denominator,
})

If the numerator isn't greater than the denominator, values are transformed so that a valid mixed fraction is created. For example:

 MixedFraction(1, 7, 3);

This constructor builds the string as '3 1/3' because '1 7/3' is not a valid input ('7/3' is not a proper fraction).

Implementation

factory MixedFraction({
  required int whole,
  required int numerator,
  required int denominator,
}) {
  // Denominator cannot be zero
  if (denominator == 0) {
    throw const MixedFractionException('The denominator cannot be zero.');
  }

  // The sign of the fractional part doesn't persist on the fraction itself;
  // the negative sign only applies (by convention) to the whole part
  final sign = Fraction(numerator, denominator).isNegative ? -1 : 1;
  final absNumerator = numerator.abs();
  final absDenominator = denominator.abs();

  // In case the numerator was greater than the denominator, there'd the need
  // to transform the fraction and make it proper. The sign of the whole part
  // may change depending on the sign of the fractional part.
  if (absNumerator > absDenominator) {
    return MixedFraction._(
      (absNumerator ~/ absDenominator + whole) * sign,
      absNumerator % absDenominator,
      absDenominator,
    );
  } else {
    return MixedFraction._(
      whole * sign,
      absNumerator,
      absDenominator,
    );
  }
}