MixedFraction.fromString constructor

MixedFraction.fromString(
  1. String value
)

Creates a MixedFraction object from value. The input string must be in the form 'a b/c' with exactly one space between the whole part and the fraction.

The fractional part can also be a glyph.

The negative sign can only stay in front of 'a' or 'b'. Some valid examples are:

 MixedFraction.fromString('-2 2/5');
 MixedFraction.fromString('1 1/3');
 MixedFraction.fromString('3 ⅐');

Implementation

factory MixedFraction.fromString(String value) {
  const errorObj = MixedFractionException(
    "The string must be in the form 'a b/c' with exactly one space between "
    'the whole part and the fraction',
  );

  // Check for the space
  if (!value.contains(' ')) {
    throw errorObj;
  }

  /*
   * The 'parts' array must contain exactly 2 pieces:
   *  - parts[0]: the whole part (an integer)
   *  - parts[1]: the fraction (a string)
   * */
  final parts = value.split(' ');

  // Throw because this is not in the form 'a b/c'
  if (parts.length != 2) {
    throw errorObj;
  }

  /*
   * At this point the string is made up of 2 "parts" separated by a space. An
   * exception can occur only if the second part is a malformed string (not a
   * fraction)
   * */
  Fraction fraction;

  // The string must be either a fraction with numbers and a slash or a glyph.
  // If that's not the case, then a 'FractionException' is thrown.
  try {
    fraction = Fraction.fromString(parts[1]);
  } on FractionException {
    fraction = Fraction.fromGlyph(parts[1]);
  }

  // Fixing the potential negative signs
  return MixedFraction(
    whole: int.parse(parts.first),
    numerator: fraction.numerator,
    denominator: fraction.denominator,
  );
}