MixedFraction constructor

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

Creates an instance of a mixed fraction.

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

MixedFraction(1, 7, 3);

... the object is built as '3 1/3' since '1 7/3' would be invalid.

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,
    );
  }
}