Skip to content

Commit

Permalink
feat: data/table: add Table.AddColumnLineNumber()
Browse files Browse the repository at this point in the history
  • Loading branch information
grokify committed Dec 27, 2024
1 parent 2bc9787 commit 857423a
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions data/table/table_column.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ package table
import (
"errors"
"fmt"
"slices"
"sort"
"strconv"
"strings"

"github.com/grokify/mogo/type/slicesutil"
)

func (tbl *Table) RowsModify(fn func(row []string) ([]string, error)) error {
func (tbl *Table) RowsModify(fn func(i int, row []string) ([]string, error)) error {
for i, row := range tbl.Rows {
if try, err := fn(row); err != nil {
if try, err := fn(i, row); err != nil {
return err
} else {
tbl.Rows[i] = try
Expand All @@ -21,6 +22,32 @@ func (tbl *Table) RowsModify(fn func(row []string) ([]string, error)) error {
return nil
}

func (tbl *Table) AddColumnLineNumber(colName string, startNumber int) (*Table, error) {
out := tbl.Clone(true)
// Update Columns
if colName == "" {
colName = "Number"
}
out.Columns = []string{colName}
out.Columns = append(out.Columns, tbl.Columns...)
// Update Format Map
out.FormatMap = map[int]string{0: FormatInt}
for k, v := range tbl.FormatMap {
if k >= 0 {
out.FormatMap[k+1] = v
} else {
out.FormatMap[k] = v
}
}
// Update Rows
err := out.RowsModify(func(i int, row []string) ([]string, error) {
outRow := []string{strconv.Itoa(i + startNumber)}
outRow = append(outRow, row...)
return slices.Clone(outRow), nil
})
return out, err
}

func (tbl *Table) ColumnsValuesDistinct(wantColNames []string, stripSpace bool) (map[string]int, error) {
data := map[string]int{}
if len(wantColNames) == 0 {
Expand Down

0 comments on commit 857423a

Please sign in to comment.