checkUnitCode method

void checkUnitCode(
  1. String code,
  2. bool primary
)

Implementation

void checkUnitCode(String code, bool primary) {
  try {
    final Term term = ExpressionParser(model).parse(code);
    final String c = ExpressionComposer().compose(term);
    if (c != code) {
      result.add('Round trip failed: $code -> $c');
    }
    Converter(model, handlers).convert(term);
  } catch (e) {
    result.add('$code: $e');
  }

  if (primary) {
    try {
      // Additional checks for primary codes
      bool inBrack = false;
      bool nonDigits = false;
      for (int i = 0; i < code.length; i++) {
        final String ch = code[i];
        if (ch == '[') {
          if (inBrack) {
            throw Exception('nested [');
          } else {
            inBrack = true;
          }
        }
        if (ch == ']') {
          if (!inBrack) {
            throw Exception('] without [');
          } else {
            inBrack = false;
          }
        }
        nonDigits =
            nonDigits || !(ch.compareTo('0') >= 0 && ch.compareTo('9') <= 0);
        if (ch.compareTo('0') >= 0 &&
            ch.compareTo('9') <= 0 &&
            !inBrack &&
            nonDigits) {
          throw Exception(
              'code $code is ambiguous because it has digits outside []');
        }
      }
    } catch (e) {
      result.add(e.toString());
    }
  }
}