-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
77 lines (60 loc) · 1.29 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
77
package cligobrr
import "fmt"
import "strings"
type TableFields struct {
Cols uint8
Pad uint8
}
type Table struct {
TableFields
lens []uint8
rows [][]string
}
func tableNew(fields TableFields) (*Table, error) {
if fields.Cols == 0 {
return nil, errTableColsRequired()
}
if fields.Pad == 0 {
fields.Pad = tablePadDefault
}
table := Table{
TableFields: fields,
lens: make([]uint8, fields.Cols, fields.Cols),
}
return &table, nil
}
func (self *Table) Add(row []string) error {
rowLen := uint8(len(row))
if rowLen != self.Cols {
return errTableRowIncorrectCols(self.Cols)
}
for i, val := range row {
valLen := uint8(len(val))
if valLen > self.lens[i] {
self.lens[i] = valLen
}
}
self.rows = append(self.rows, row)
return nil
}
func (self *Table) normalize() {
for _, row := range self.rows {
for i, cell := range row {
cellLen := uint8(len(cell))
padLen := self.lens[i] - cellLen
if padLen > 0 {
pad := strings.Repeat(" ", int(padLen))
row[i] = fmt.Sprintf("%s%s", cell, pad)
}
}
}
}
func (self *Table) ToString() string {
var output []string
self.normalize()
padding := strings.Repeat(" ", int(self.Pad))
for _, row := range self.rows {
output = append(output, strings.Join(row, padding))
}
return strings.Join(output, "\n")
}