Skip to content

Commit

Permalink
feat: strconv/strconvutil: add SliceAtou(); canonicalize others
Browse files Browse the repository at this point in the history
  • Loading branch information
grokify committed Nov 26, 2023
1 parent 6bb319b commit 126f3c3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 36 deletions.
64 changes: 42 additions & 22 deletions strconv/strconvutil/slice.go
Original file line number Diff line number Diff line change
@@ -1,41 +1,61 @@
package strconvutil

import (
"sort"
"strconv"

"github.com/grokify/mogo/type/slicesutil"
"golang.org/x/exp/constraints"
)

// SliceAtoi converts a slice of string integers.
func SliceAtoi(strings []string) ([]int, error) {
ints := []int{}
for _, s := range strings {
thisInt, err := strconv.Atoi(s)
func SliceAtoi(s []string, dedupe, sort bool) ([]int, error) {
out := []int{}
for _, si := range s {
sv, err := strconv.Atoi(si)
if err != nil {
return ints, err
return []int{}, err
}
ints = append(ints, thisInt)
out = append(out, sv)
}
return ints, nil
if dedupe {
out = slicesutil.Dedupe(out)
}
if sort {
slicesutil.Sort(out)
}
return out, nil
}

// SliceAtoiSort converts and sorts a slice of string integers.
func SliceAtoiSort(strings []string) ([]int, error) {
ints, err := SliceAtoi(strings)
if err != nil {
return ints, err
}
intSlice := sort.IntSlice(ints)
intSlice.Sort()
return intSlice, nil
func SliceAtou(s []string, dedupe, sort bool) ([]uint, error) {
out := []uint{}
for _, si := range s {
sv, err := Atou(si)
if err != nil {
return []uint{}, err
} else {
out = append(out, sv)
}
}
if dedupe {
out = slicesutil.Dedupe(out)
}
if sort {
slicesutil.Sort(out)
}
return out, nil
}

// SliceItoa converts a slice of `constraints.Integer` to a slice of `string`.
func SliceItoa[S ~[]E, E constraints.Integer](elems S) []string {
strs := []string{}
for _, v := range elems {
strs = append(strs, strconv.Itoa(int(v)))
func SliceItoa[S ~[]E, E constraints.Integer](s S, dedupe, sort bool) []string {
out := []string{}
for _, v := range s {
out = append(out, strconv.Itoa(int(v)))
}
if dedupe {
out = slicesutil.Dedupe(out)
}
if sort {
slicesutil.Sort(out)
}
return strs
return out
}
14 changes: 0 additions & 14 deletions type/slicesutil/strconv.go

This file was deleted.

0 comments on commit 126f3c3

Please sign in to comment.