Skip to content

Instantly share code, notes, and snippets.

@prathyvsh
Last active May 7, 2020 21:16
Show Gist options
  • Save prathyvsh/610aad13cc0c3a126999ddaf3201dc9f to your computer and use it in GitHub Desktop.
Save prathyvsh/610aad13cc0c3a126999ddaf3201dc9f to your computer and use it in GitHub Desktop.
Leaderboard
import "dart:math";
List<List<String>> csv;
void main() {
csv = [
["1", "Orange", "3"],
["2", "Apple", "4"],
["3", "Lemon", "4"],
["42", "Grapes", "6"]
];
int getMaxLength(Iterable names) {
return names
.map<int>((n) => (n is num ? n.toString().length : n.length))
.reduce(max);
}
String lpad(str, len) {
int diff = max(0, len - str.length);
return (" " * diff) + str;
}
String rpad(str, len) {
int diff = max(0, len - str.length);
return str + (" " * diff);
}
String col(List items) => "| " + items.join(" | ") + " |";
String leaderboard(List data) {
int col1Max = max("ID".length, getMaxLength(data.map((list) => list[0])));
int col2Max =
max("Teams".length, getMaxLength(data.map((list) => list[1])));
int col3Max =
max("Points".length, getMaxLength(data.map((list) => list[2])));
String topHeader = "** Leaderboard **\n";
String header = col(
[rpad("ID", col1Max), rpad("Team", col2Max), rpad("Points", col3Max)]);
String div = "-" * header.length;
String rows = (data.fold<List<String>>(
[],
(init, v) => [
...init,
col([
lpad(v[0].toString(), col1Max),
rpad(v[1].toString(), col2Max),
lpad(v[2].toString(), col3Max)
])
]).join("\n"));
return [topHeader, header, div, rows].join("\n");
}
print(leaderboard(csv));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment