Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Last active September 9, 2020 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukepighetti/3b272cf32b6e5946f92ea48aca51548b to your computer and use it in GitHub Desktop.
Save lukepighetti/3b272cf32b6e5946f92ea48aca51548b to your computer and use it in GitHub Desktop.
Table formatting helper for console outputs https://twitter.com/luke_pighetti/status/1303736288315572224
import 'dart:math';
class Table {
/// Example output
///
/// ```
/// Range (yd) 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
/// Drop (in) -0.51, 0.06, 0.23, -0.03, -0.71, -1.84, -3.42, -5.46, -7.98, -10.99
/// Drop (moa) 4.78, -0.31, -0.73, 0.06, 1.35, 2.92, 4.65, 6.51, 8.45, 10.48
/// Windage (in) 0.03, 0.05, 0.09, 0.15, 0.22, 0.31, 0.41, 0.53, 0.66, 0.81
/// Windage (moa) 0.27, 0.25, 0.29, 0.35, 0.42, 0.49, 0.56, 0.63, 0.70, 0.78
/// ```
Table(this.rows)
: assert(rows.every((row) => row.cells.length == rows.first.cells.length),
'Every row needs the same number of cells');
final List<Row> rows;
int get maxTitleLength =>
rows.fold(0, (last, row) => max(row.title.length, last));
int get maxUnitLength =>
rows.fold(0, (last, row) => max(row.unit.length, last));
int get maxCellWidth {
var width = 0;
for (var row in rows) {
for (var cell in row.cells) {
width = max(width, cell.toString().length);
}
}
return width;
}
@override
String toString() {
return rows
.map((e) => e.format(maxTitleLength, maxUnitLength, maxCellWidth))
.join('\n');
}
}
class Row {
/// A row to be formatted within a [Table]
Row(this.title, this.unit, this.cells);
final String title;
final String unit;
final Iterable<dynamic> cells;
String format(int maxTitleLength, int maxUnitLength, int maxCellWidth) {
final formattedTitle = title.padLeft(maxTitleLength);
final formattedUnit = '($unit)'.padLeft(maxUnitLength + 2);
final formattedCells = cells.map((e) => '$e'.padLeft(maxCellWidth));
return '$formattedTitle $formattedUnit ${formattedCells.join(", ")}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment