condenseUnicodeSequences function

String? condenseUnicodeSequences(
  1. String? input
)

Implementation

String? condenseUnicodeSequences(String? input) {
  if (input == null) return null;

  final regex = RegExp(
      r'[\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207B]{2,}');
  final superscriptToValue = {
    '\u{2070}': 0,
    '\u{00B9}': 1,
    '\u{00B2}': 2,
    '\u{00B3}': 3,
    '\u{2074}': 4,
    '\u{2075}': 5,
    '\u{2076}': 6,
    '\u{2077}': 7,
    '\u{2078}': 8,
    '\u{2079}': 9,
  };

  String digitToSuperscript(int digit) {
    if (digit == 0) return '\u{2070}';
    if (digit == 1) return '\u{00B9}';
    if (digit == 2) return '\u{00B2}';
    if (digit == 3) return '\u{00B3}';
    return String.fromCharCode(0x2070 + digit);
  }

  // Find all matches
  final matches = regex.allMatches(input).toList();
  if (matches.isEmpty) {
    return input; // No sequences found
  }

  // Build the result string step-by-step
  final buffer = StringBuffer();
  int previousEnd = 0;

  for (final match in matches) {
    // Add any text before the current match
    buffer.write(input.substring(previousEnd, match.start));

    final sequence = match.group(0)!;
    int sign = 1;
    int product = 1;

    // Calculate the product of the numbers in the superscript sequence
    for (var char in sequence.split('')) {
      if (char == '\u{207B}') {
        sign *= -1;
      } else {
        final value =
            superscriptToValue[char] ?? 1; // Default to 1 if unrecognized
        product *= value;
      }
    }

    // Determine the combined sign
    final combinedSign = sign == -1 ? '\u{207B}' : '';

    // Convert the product back to superscript format
    final productDigits = product.toString().split('');
    final combinedExponent = productDigits.map((digit) {
      final digitValue = int.parse(digit);
      return digitToSuperscript(digitValue);
    }).join('');

    // Replace the current sequence in the result
    buffer.write(combinedSign + combinedExponent);

    // Update the previousEnd to the end of the current match
    previousEnd = match.end;
  }

  // Add any remaining text after the last match
  buffer.write(input.substring(previousEnd));

  return buffer.toString();
}