tryParse static method

Complex? tryParse(
  1. String source
)

Parses source as a Complex. Returns null in case of a problem.

Implementation

static Complex? tryParse(String source) {
  final parts = numberAndUnitExtractor
      .allMatches(source.replaceAll(' ', ''))
      .where((match) => match.start < match.end)
      .toList();
  if (parts.isEmpty) {
    return null;
  }
  num a = 0, b = 0;
  final seen = <String>{};
  for (final part in parts) {
    final numberString = part.group(1) ?? '';
    final number = num.tryParse(numberString);
    final unitString = part.group(4) ?? '';
    final unit = unitString.toLowerCase();
    if (seen.contains(unit)) {
      return null; // repeated unit
    }
    if (unit == '' && number != null) {
      a = number;
    } else if (numberString.isEmpty || number != null) {
      if (unit == 'i') {
        b = number ?? 1;
      } else {
        return null; // invalid unit
      }
    } else {
      return null; // parse error
    }
    seen.add(unit);
  }
  return Complex(a, b);
}