Rational.parse constructor

Rational.parse(
  1. String source
)

Parses source as a Rational.

Example:

Rational.parse('1 1/2') == const Rational.fromMixed(1, 1, 2)
Rational.parse('3/4') == const Rational(3, 4)
Rational.parse('-35/4') == const Rational.fromMixed(-8, 3, 4)

Implementation

factory Rational.parse(String source) {
  final match =
      _regExp.firstMatch(source) ??
      (throw FormatException('Invalid Ratio', source));

  final integer = int.parse(match.namedGroup('integer')!);
  final numerator = match.namedGroup('numerator');

  if (numerator != null) {
    final denominator = match.namedGroup('denominator')!;

    return .fromMixed(integer, .parse(numerator), .parse(denominator));
  }

  final denominator = match.namedGroup('fractionDenominator');
  if (denominator == null) return .fromMixed(integer);

  return Rational(integer, .parse(denominator));
}