-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
62 lines (50 loc) · 1.12 KB
/
table.go
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
package lazysupport
import (
"fmt"
"strconv"
"strings"
)
type Table struct {
Header []string
Values [][]string
}
type tableWidth []int
func (t *Table) updateTableWidth(tw *tableWidth, row []string) {
for missingWidths := len(row) - len(*tw); missingWidths > 0; missingWidths = missingWidths - 1 {
*tw = append(*tw, 0)
}
for i, col := range row {
width := len(col)
if (*tw)[i] < width {
(*tw)[i] = width
}
}
}
func (t *Table) renderRow(tw *tableWidth, row []string) string {
content := ""
for i, col := range row {
format := "%-" + strconv.Itoa((*tw)[i]) + "s "
content = content + fmt.Sprintf(format, col)
}
return strings.TrimSpace(content)
}
func (t *Table) String() string {
// Calculate columns space
var tw tableWidth
t.updateTableWidth(&tw, t.Header)
for _, row := range t.Values {
t.updateTableWidth(&tw, row)
}
if len(tw) == 0 {
return ""
}
// Render the table
var lines []string
if t.Header != nil {
lines = append(lines, t.renderRow(&tw, t.Header))
}
for _, row := range t.Values {
lines = append(lines, t.renderRow(&tw, row))
}
return strings.Join(lines, "\n") + "\n"
}