-
Notifications
You must be signed in to change notification settings - Fork 0
/
tables.dart
99 lines (79 loc) · 2.28 KB
/
tables.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class Table {
final List<Column> columns;
const Table(this.columns);
String generate(Iterable<List<dynamic>> values) {
String result = headers;
for(List<dynamic> row in values) {
result += '\n|';
for(int i = 0; i < columns.length; i++) {
String value = columns[i].process(row[i]);
result += ' $value |';
}
}
return result;
}
String get headers {
String row1 = '|';
String row2 = '|';
for(Column column in columns) {
row1 += ' ${column.title} |';
switch(column.alignment) {
case Alignment.LEFT:
row2 += ' --- |';
break;
case Alignment.CENTER:
row2 += ':---:|';
break;
case Alignment.RIGHT:
row2 += ' ---:|';
break;
}
}
return '$row1\n$row2';
}
}
typedef String Processor<T>(T value);
String defaultProcessor(dynamic value) => value as String;
String defaultNumericProcessor(dynamic value) {
String withComma = value.toString().replaceAll('.', ',');
String withDotSeperation = '';
int commaIndex = -1;
for(int i = withComma.length - 1; i >= 0; i--) {
if(commaIndex != -1) {
if(i - commaIndex != -1 && ((i - commaIndex + 1) % 3 == 0) && withComma[i] != '-') {
withDotSeperation = '.$withDotSeperation';
}
withDotSeperation = '${withComma[i]}$withDotSeperation';
} else {
withDotSeperation = '${withComma[i]}$withDotSeperation';
if(withComma[i] == ',') commaIndex = i;
}
}
return withDotSeperation;
}
String defaultBooleanProcessor(dynamic value) => value as bool ? '✔️' : '❌';
enum Alignment {
LEFT, CENTER, RIGHT
}
class Column<T> {
String title;
Alignment alignment;
Processor process;
Column(this.title, {this.alignment = Alignment.LEFT, this.process = defaultProcessor});
}
class NumericColumn extends Column<num> {
NumericColumn(
String title,
{
Alignment alignment = Alignment.LEFT,
Processor<num> process = defaultNumericProcessor
}) : super(title, alignment: alignment, process: process);
}
class BooleanColumn extends Column<bool> {
BooleanColumn(
String title,
{
Alignment alignment = Alignment.LEFT,
Processor<num> process = defaultBooleanProcessor
}) : super(title, alignment: alignment, process: process);
}