table static method

Future<void> table(
  1. List<List<String>> rows, {
  2. List<String>? header,
})

Implementation

static Future<void> table(List<List<String>> rows, {List<String>? header}) async {
  int columnCount = header?.length ?? rows[0].length;
  List<int> columnWidths = List<int>.filled(columnCount + 1, 0);

  if (header != null) {
    header.insert(0, '#');
    for (int i = 0; i < columnCount + 1; i++) {
      columnWidths[i] = max(columnWidths[i], header[i].length);
    }
  }

  for (int i = 0; i < columnCount; i++) {
    columnWidths[i + 1] = rows.fold(columnWidths[i + 1], (maximum, row) => max(maximum, row[i].length));
  }

  if (header != null) {
    for (int i = 0; i < columnCount + 1; i++) {
      stdout.write(header[i].padRight(columnWidths[i] + 2));
      if (i < columnCount) {
        stdout.write('| ');
      }
    }
    stdout.writeln();
    stdout.writeln('-' * columnWidths.reduce((a, b) => a + b + 2 * (columnCount + 1) + columnCount * 2));
  }

  for (int i = 0; i < rows.length; i++) {
    stdout.write((i + 1).toString().padRight(columnWidths[0] + 2));
    stdout.write('| ');
    for (int j = 0; j < columnCount; j++) {
      stdout.write(rows[i][j].padRight(columnWidths[j + 1] + 2));
      if (j < columnCount - 1) {
        stdout.write('| ');
      }
    }
    stdout.writeln();
  }
}