Skip to content

Commit dd2c0d2

Browse files
committed
enhance: table: add Table.String()
1 parent 73cc072 commit dd2c0d2

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

data/table/format.go

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
package table
22

33
import (
4+
"bytes"
5+
"encoding/csv"
46
"errors"
57
"fmt"
8+
"strings"
69

710
"github.com/grokify/simplego/math/mathutil"
811
)
912

10-
// FormatStraightToTabular takes a "straight table" wheere the columnn names
13+
// Pivot takes a "straight table" where the columnn names
1114
// and values are in a single column and lays it out as a standard tabular data.
12-
func FormatStraightToTabular(tbl Table, colCount uint) (Table, error) {
15+
func (tbl *Table) Pivot(colCount uint) (Table, error) {
1316
newTbl := NewTable(tbl.Name)
1417
if len(tbl.Columns) != 0 {
15-
return newTbl, fmt.Errorf("Has Defined Columns Count [%d]", len(tbl.Columns))
18+
return newTbl, fmt.Errorf("has defined columns count [%d]", len(tbl.Columns))
1619
}
1720
isWellFormed, colCountActual := tbl.IsWellFormed()
1821
if !isWellFormed {
@@ -41,3 +44,29 @@ func FormatStraightToTabular(tbl Table, colCount uint) (Table, error) {
4144
}
4245
return newTbl, nil
4346
}
47+
48+
// String writes the table out to a CSV string.
49+
func (tbl *Table) String(comma rune, useCRLF bool) (string, error) {
50+
var b bytes.Buffer
51+
w := csv.NewWriter(&b)
52+
w.Comma = comma
53+
w.UseCRLF = useCRLF
54+
defer w.Flush()
55+
56+
if len(tbl.Columns) > 0 {
57+
if err := w.Write(tbl.Columns); err != nil {
58+
return "", fmt.Errorf("error writing columns to csv [%s]",
59+
strings.Join(tbl.Columns, ","))
60+
}
61+
}
62+
63+
for _, row := range tbl.Rows {
64+
if err := w.Write(row); err != nil {
65+
return "", fmt.Errorf("error writing row to csv [%s]",
66+
strings.Join(row, ","))
67+
}
68+
}
69+
70+
w.Flush()
71+
return b.String(), w.Error()
72+
}

0 commit comments

Comments
 (0)