productUnitParser property

Parser<Unit> productUnitParser

Returns a typed parser that produces a unit or a rational product of unit.

Implementation

Parser<Unit> get productUnitParser {
  var term = undefined<Unit>();

  var paren =
      (char('(').trim() & term & char(')').trim()).pick(1).cast<Unit>();

  var e = (anyOf('^¹²³').and() & _exponent).pick(1).cast<RationalNumber>();

  var base =
      paren | singleUnitParser | _integer().map((v) => Unit.one.scaled(v));

  var element = (base & e.optionalWith(RationalNumber.one))
      .map((l) => RationalPower<Unit>(l[0], l[1]));

  var divisor = (char('/') & element).pick(1).map((v) => v.inverse);
  var factor = (element & divisor.star()).map(
      (l) => ProductUnit([l[0], ...(l[1] as Iterable).cast()]).simplify());
  term.set(factor.separatedBy(char('*')).map((l) =>
      l.length == 1 ? l.first : ProductUnit(l.map((v) => RationalPower(v)))));

  var number =
      _mapParser(anyOf('012356789+-.E').plus().flatten(), (dynamic v) {
    try {
      return epsilonWith(num.parse(v));
    } catch (e) {
      return failure('$e');
    }
  });
  return (term & (char('+') & number).pick(1).optional())
      .map((l) => l[1] == null ? l[0] : l[0].plus(l[1]));
}