/
table.go
76 lines (67 loc) · 1.35 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"fmt"
"io"
"strings"
)
// Table formats for output data structured in rows and columns
type Table struct {
Columns []string
Rows [][]string
}
// Print outputs the table to a writer with a given width (to avoid wrapping fields may be truncated)
func (t *Table) Print(w io.Writer, width int) {
colWidths := make([]int, len(t.Columns))
updateColWidths(t.Columns, &colWidths)
for _, r := range t.Rows {
updateColWidths(r, &colWidths)
}
totalWidth := 0
largestCol := 0
for i, c := range colWidths {
if c > colWidths[largestCol] {
largestCol = i
}
if i > 0 {
totalWidth++
}
totalWidth += c
}
toCut := totalWidth - width
if toCut > 0 {
colWidths[largestCol] -= toCut
}
line := ""
for i, c := range t.Columns {
if i > 0 {
line += " "
}
line += fmt.Sprintf("%*.*s", -colWidths[i], colWidths[i], c)
}
fmt.Fprintln(w, line)
line = ""
for i := range t.Columns {
if i > 0 {
line += " "
}
line += strings.Repeat("=", colWidths[i])
}
fmt.Fprintln(w, line)
for _, r := range t.Rows {
line = ""
for i, c := range r {
if i > 0 {
line += " "
}
line += fmt.Sprintf("%*.*s", -colWidths[i], colWidths[i], c)
}
fmt.Fprintln(w, line)
}
}
func updateColWidths(a []string, colWidths *[]int) {
for i, v := range a {
if len(v) > (*colWidths)[i] {
(*colWidths)[i] = len(v)
}
}
}