3
0

Add HasString and PluckString to slice pkg

This commit is contained in:
Denis Arh 2020-01-29 08:15:17 +01:00
parent 2f9d3fb039
commit 4cf645d11a
2 changed files with 181 additions and 0 deletions

View File

@ -23,3 +23,32 @@ func ToStringBoolMap(s []string) (h map[string]bool) {
return
}
func HasString(ss []string, s string) bool {
for i := range ss {
if ss[i] == s {
return true
}
}
return false
}
// RemoveString removes one or more strings form the input slice
func PluckString(ss []string, ff ...string) (o []string) {
if len(ff) == 0 {
return ss
}
f := ToStringBoolMap(ff)
o = make([]string, 0, len(ss))
for _, s := range ss {
if !f[s] {
// remove from the list
o = append(o, s)
}
}
return o
}

152
pkg/slice/strings_test.go Normal file
View File

@ -0,0 +1,152 @@
package slice
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestIntersectStrings(t *testing.T) {
cases := []struct {
name string
a []string
b []string
c []string
}{
{
"empty",
[]string{},
[]string{},
[]string{},
},
{
"none",
[]string{"a"},
[]string{"b"},
[]string{},
},
{
"some",
[]string{"a", "b"},
[]string{"a", "c"},
[]string{"a"},
},
{
"all",
[]string{"a", "b"},
[]string{"a", "b"},
[]string{"a", "b"},
},
{
"dups",
[]string{"a", "b", "b", "b"},
[]string{"a", "b"},
[]string{"a", "b"},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.EqualValues(t, IntersectStrings(c.a, c.b), c.c)
})
}
}
func TestToStringBoolMap(t *testing.T) {
cases := []struct {
name string
i []string
o map[string]bool
}{
{
"empty",
[]string{},
map[string]bool{},
},
{
"some",
[]string{"a"},
map[string]bool{"a": true},
},
{
"many",
[]string{"a", "b", "c", "c", "d"},
map[string]bool{"a": true, "b": true, "c": true, "d": true},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.EqualValues(t, ToStringBoolMap(c.i), c.o)
})
}
}
func TestHasString(t *testing.T) {
cases := []struct {
name string
ss []string
s string
o bool
}{
{
"empty",
[]string{},
"a",
false,
},
{
"has not",
[]string{"a"},
"b",
false,
},
{
"has",
[]string{"a"},
"a",
true,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.EqualValues(t, HasString(c.ss, c.s), c.o)
})
}
}
func TestPluckStrung(t *testing.T) {
cases := []struct {
name string
ss []string
ff []string
o []string
}{
{
"empty",
[]string{},
[]string{},
[]string{},
},
{
"some",
[]string{"a", "b"},
[]string{"a"},
[]string{"b"},
},
{
"all",
[]string{"a", "b"},
[]string{"a", "b"},
[]string{},
},
{
"not there",
[]string{"a"},
[]string{"b"},
[]string{"a"},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.EqualValues(t, HasString(c.ss, c.s), c.o)
})
}
}