2022-03-17 00:33:59 +00:00
|
|
|
package stringslice
|
2019-02-09 12:30:49 +00:00
|
|
|
|
2022-12-01 02:54:08 +00:00
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
2020-07-19 01:59:18 +00:00
|
|
|
|
2021-01-18 01:23:20 +00:00
|
|
|
// StringSliceToIntSlice converts a slice of strings to a slice of ints.
|
|
|
|
// Returns an error if any values cannot be parsed.
|
|
|
|
func StringSliceToIntSlice(ss []string) ([]int, error) {
|
2020-07-19 01:59:18 +00:00
|
|
|
ret := make([]int, len(ss))
|
|
|
|
for i, v := range ss {
|
2021-01-18 01:23:20 +00:00
|
|
|
var err error
|
|
|
|
ret[i], err = strconv.Atoi(v)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-07-19 01:59:18 +00:00
|
|
|
}
|
|
|
|
|
2021-01-18 01:23:20 +00:00
|
|
|
return ret, nil
|
2020-07-19 01:59:18 +00:00
|
|
|
}
|
2022-12-01 02:54:08 +00:00
|
|
|
|
|
|
|
// FromString converts a string to a slice of strings, splitting on the sep character.
|
|
|
|
// Unlike strings.Split, this function will also trim whitespace from the resulting strings.
|
|
|
|
func FromString(s string, sep string) []string {
|
|
|
|
v := strings.Split(s, ",")
|
|
|
|
for i, vv := range v {
|
|
|
|
v[i] = strings.TrimSpace(vv)
|
|
|
|
}
|
|
|
|
return v
|
|
|
|
}
|
2024-05-08 02:47:18 +00:00
|
|
|
|
|
|
|
// Unique returns a slice containing only unique values from the provided slice.
|
|
|
|
// The comparison is case-insensitive.
|
|
|
|
func UniqueFold(s []string) []string {
|
|
|
|
seen := make(map[string]struct{})
|
|
|
|
var ret []string
|
|
|
|
for _, v := range s {
|
|
|
|
if _, exists := seen[strings.ToLower(v)]; exists {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
seen[strings.ToLower(v)] = struct{}{}
|
|
|
|
ret = append(ret, v)
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|