Add possibility to set a max width for each column

main
Stefano 2021-11-17 21:32:38 +01:00
parent d705166019
commit b465f6e9b6
1 changed files with 15 additions and 3 deletions

View File

@ -8,9 +8,10 @@ import (
type Row []string
type TablePrinter struct {
Headers []string
Rows []Row
MaxRows int
Headers []string
Rows []Row
MaxRows int
MaxWidths []int
}
func NewTablePrinter(headers []string) *TablePrinter {
@ -20,6 +21,10 @@ func NewTablePrinter(headers []string) *TablePrinter {
}
}
func (printer *TablePrinter) SetMaxWidths(widths []int) {
printer.MaxWidths = widths
}
func centerString(s string, width int) string {
padSpace := width - len(s)
leftPadding := padSpace / 2
@ -70,6 +75,13 @@ func (printer *TablePrinter) computeColumnWidthds() []int {
for i := 0; i < printer.NumCols(); i++ {
widths[i] += paddingDefault
if printer.MaxWidths != nil {
if printer.MaxWidths[i] > 0 && widths[i] > printer.MaxWidths[i] {
widths[i] = printer.MaxWidths[i]
}
}
}
return widths
}