-
Notifications
You must be signed in to change notification settings - Fork 4
/
expand.go
86 lines (82 loc) · 2.24 KB
/
expand.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
78
79
80
81
82
83
84
85
86
package table
import (
"errors"
"strconv"
"strings"
"github.com/grokify/mogo/type/stringsutil"
)
const (
ColNameNone = "(none)"
ColNameCount = "(count)"
)
// ColumnExpandPivot adds columns to the table representing each value in the provided column.
func (tbl *Table) ColumnExpandPivot(colIdx uint, split bool, sep, colNamePrefix, colNameNone, existString, notExistString string, addCounts bool, colNameCounts string) (map[int]string, error) {
colFormats := map[int]string{}
if int(colIdx) >= len(tbl.Columns) {
return colFormats, errors.New("colIdx is too large")
}
isWellFormed, _, _ := tbl.IsWellFormed()
if !isWellFormed {
return colFormats, errors.New("table is not well formed. Cannot expand")
}
newColVals, _, err := tbl.ColumnValuesSplit(colIdx, split, sep, true, true)
if err != nil {
return colFormats, err
}
colNamePrefix = strings.TrimSpace(colNamePrefix)
if len(colNamePrefix) == 0 {
colNamePrefix = tbl.Columns[colIdx]
}
for _, v := range newColVals {
v = strings.TrimSpace(v)
if len(v) == 0 {
if len(strings.TrimSpace(colNameNone)) > 0 {
v = colNameNone
} else {
v = ColNameNone
}
}
newColName := colNamePrefix + ": " + v
tbl.Columns = append(tbl.Columns, newColName)
}
if addCounts {
colNameCountsActual := colNameCounts
if len(strings.TrimSpace(colNameCountsActual)) == 0 {
colNameCountsActual = ColNameCount
}
tbl.Columns = append(tbl.Columns, colNamePrefix+": "+colNameCountsActual)
}
rowColVals := 0
for i, row := range tbl.Rows {
for _, newColVal := range newColVals {
exist := false
if !split {
row[colIdx] = strings.TrimSpace(row[colIdx])
if newColVal == row[colIdx] {
exist = true
}
if len(row[colIdx]) > 0 {
rowColVals = 1
}
} else {
rowVals := stringsutil.SliceCondenseSpace(strings.Split(row[colIdx], sep), true, true)
if stringsutil.SliceIndex(rowVals, newColVal, false, nil) > -1 {
exist = true
}
rowColVals = len(rowVals)
}
if exist {
row = append(row, existString)
} else {
row = append(row, notExistString)
}
}
if addCounts {
row = append(row, strconv.Itoa(rowColVals))
colFormats[len(row)-1] = FormatInt
tbl.FormatMap[len(row)-1] = FormatInt
}
tbl.Rows[i] = row
}
return colFormats, nil
}