format method

String format({
  1. bool limit = true,
  2. int leadingItems = 3,
  3. int trailingItems = 3,
  4. Printer<String>? ellipsesPrinter,
  5. Printer<String>? paddingPrinter,
  6. Printer<T>? valuePrinter,
  7. String addition = ' + ',
  8. String ellipses = '\u2026',
  9. String multiplication = '',
  10. String power = '^',
  11. String variable = 'x',
  12. bool skipNulls = true,
  13. bool skipValues = true,
})

Returns a human readable representation of the polynomial.

Implementation

String format({
  bool limit = true,
  int leadingItems = 3,
  int trailingItems = 3,
  Printer<String>? ellipsesPrinter,
  Printer<String>? paddingPrinter,
  Printer<T>? valuePrinter,
  String addition = ' + ',
  String ellipses = '\u2026',
  String multiplication = '',
  String power = '^',
  String variable = 'x',
  bool skipNulls = true,
  bool skipValues = true,
}) {
  ellipsesPrinter ??= const StandardPrinter<String>();
  paddingPrinter ??= const StandardPrinter<String>();
  valuePrinter ??= dataType.printer;

  String? coefficientPrinter(int exponent, T coefficient) {
    if (skipNulls && dataType.field.additiveIdentity == coefficient) {
      return null;
    }
    final buffer = StringBuffer();
    final skipValue = skipValues &&
        exponent != 0 &&
        coefficient == dataType.field.multiplicativeIdentity;
    if (!skipValue) {
      buffer.write(valuePrinter!(coefficient));
    }
    if (exponent > 0) {
      if (!skipValue) {
        buffer.write(multiplication);
      }
      buffer.write(variable);
      if (exponent > 1) {
        buffer.write(power);
        buffer.write(exponent);
      }
    }
    return buffer.toString();
  }

  final count = degree;
  if (count < 0) {
    return paddingPrinter(valuePrinter(dataType.field.additiveIdentity));
  }
  final parts = <String>[];
  for (var i = count; i >= 0; i--) {
    final part = coefficientPrinter(i, getUnchecked(i));
    if (part != null) {
      parts.add(part);
    }
  }
  final buffer = StringBuffer();
  for (var i = 0; i < parts.length; i++) {
    if (i > 0) {
      buffer.write(addition);
    }
    if (limit && leadingItems <= i && i < count - trailingItems) {
      buffer.write(paddingPrinter(ellipsesPrinter(ellipses)));
      i = count - trailingItems - 1;
    } else {
      buffer.write(paddingPrinter(parts[i]));
    }
  }
  return buffer.toString();
}