toInt method

int? toInt()

Attempts to evaluate a Roman numeral as an integer

Evaluates a Roman numeral string as an integer.

Returns the integer value, or null if value is empty or contains any character that is not a recognised Roman numeral digit.

Allows additive repetition (e.g. "IIII" is accepted as 4, even though the canonical form is "IV").

Implementation

int? toInt() {
  // go backwards through the digits
  var total = 0;
  var prevDigit = 0;
  final reversed = value.characters.toList().reversed;

  for (final c in reversed) {
    var n = romanDigits[c];

    if (n == null) {
      return null;
    }

    if (n < prevDigit) {
      // e.g. ix
      total -= n;
    } else {
      total += n;
    }
    prevDigit = n;
  }
  return total;
}