Skip to content

Commit c1058ff

Browse files
committed
enhance: table: enable Table.Pivot() to add Columns
1 parent 6304986 commit c1058ff

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

data/table/format.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212

1313
// Pivot takes a "straight table" where the columnn names
1414
// and values are in a single column and lays it out as a standard tabular data.
15-
func (tbl *Table) Pivot(colCount uint) (Table, error) {
15+
func (tbl *Table) Pivot(colCount uint, haveColumns bool) (Table, error) {
1616
newTbl := NewTable(tbl.Name)
1717
if len(tbl.Columns) != 0 {
1818
return newTbl, fmt.Errorf("has defined columns count [%d]", len(tbl.Columns))
@@ -28,19 +28,30 @@ func (tbl *Table) Pivot(colCount uint) (Table, error) {
2828
if remainder != 0 {
2929
return newTbl, fmt.Errorf("row count [%d] is not a multiple of col count [%d]", rowCount, colCount)
3030
}
31+
addedColumns := false
3132
newRow := []string{}
3233
for i, row := range tbl.Rows {
3334
_, remainder := mathutil.DivideInt64(int64(i), int64(colCount))
3435
if remainder == 0 {
3536
if len(newRow) > 0 {
36-
newTbl.Rows = append(newTbl.Rows, newRow)
37+
if haveColumns && !addedColumns {
38+
newTbl.Columns = newRow
39+
addedColumns = true
40+
} else {
41+
newTbl.Rows = append(newTbl.Rows, newRow)
42+
}
3743
newRow = []string{}
3844
}
3945
}
4046
newRow = append(newRow, row[0])
4147
}
4248
if len(newRow) > 0 {
43-
newTbl.Rows = append(newTbl.Rows, newRow)
49+
if haveColumns && !addedColumns {
50+
newTbl.Columns = newRow
51+
addedColumns = true
52+
} else {
53+
newTbl.Rows = append(newTbl.Rows, newRow)
54+
}
4455
}
4556
return newTbl, nil
4657
}

0 commit comments

Comments
 (0)