-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonly.go
More file actions
53 lines (46 loc) · 1.34 KB
/
Copy pathonly.go
File metadata and controls
53 lines (46 loc) · 1.34 KB
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
package simplecsv
// OnlyThisRows removes all rows that are not in the index and sorts the csv by the index order
// All rows must exist or it fails
// If header is true, the header row is always the first row of the result,
// so including 0 in rowsIndex duplicates the header row in the result
func (s SimpleCsv) OnlyThisRows(rowsIndex []int, header bool) (SimpleCsv, bool) {
lengthS := len(s)
for _, v := range rowsIndex {
if v < 0 || v >= lengthS {
return s.fail()
}
}
newCsv := SimpleCsv{}
if header {
headers := s.GetHeaders()
newCsv = append(newCsv, headers)
}
var rowToAdd []string
for _, g := range rowsIndex {
rowToAdd, _ = s.GetRow(g)
newCsv = append(newCsv, rowToAdd)
}
return newCsv, true
}
// OnlyThisFields returns a simplecsv with the fields. At least one field name
// is required (empty or nil fields is rejected).
func (s SimpleCsv) OnlyThisFields(fields []string) (SimpleCsv, bool) {
positions := s.headerIndex()
newCsv, err := CreateEmptyCsv(fields)
if err != nil {
return s.fail()
}
for i := 1; i < len(s); i++ {
row := make([]string, 0, len(fields))
for _, field := range fields {
column, fieldExists := positions[field]
if fieldExists && column < len(s[i]) {
row = append(row, s[i][column])
} else {
row = append(row, "")
}
}
newCsv, _ = newCsv.AddRow(row)
}
return newCsv, true
}