From b465f6e9b61c8e971d4eded5c0d26cd915b76891 Mon Sep 17 00:00:00 2001 From: Stefano Date: Wed, 17 Nov 2021 21:32:38 +0100 Subject: [PATCH] Add possibility to set a max width for each column --- table.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/table.go b/table.go index 58561f3..907a5f6 100644 --- a/table.go +++ b/table.go @@ -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 }