Optimize: utils.Contains applicable to more types

This commit is contained in:
demoManito 2022-09-08 13:46:08 +08:00
parent b3eb1c8c51
commit fc8bb273c8
2 changed files with 28 additions and 3 deletions

View File

@ -69,9 +69,14 @@ func ToStringKey(values ...interface{}) string {
return strings.Join(results, "_")
}
func Contains(elems []string, elem string) bool {
for _, e := range elems {
if elem == e {
func Contains(elems interface{}, elem interface{}) bool {
reflectValue := reflect.ValueOf(elems)
if reflectValue.Kind() != reflect.Slice && reflectValue.Kind() != reflect.Array {
return false
}
for i := 0; i < reflectValue.Len(); i++ {
if reflectValue.Index(i).Interface() == elem {
return true
}
}

View File

@ -29,3 +29,23 @@ func TestToStringKey(t *testing.T) {
}
}
}
func TestContains(t *testing.T) {
tests := []struct {
elems interface{}
elem interface{}
target bool
}{
{elems: []string{"INSERT", "VALUES", "ON CONFLICT", "RETURNING"}, elem: "RETURNING", target: true},
{elems: []string{"INSERT", "VALUES", "ON CONFLICT"}, elem: "RETURNING", target: false},
{elems: []int{1, 2, 3}, elem: 1, target: true},
{elems: []interface{}{1, 2.0, "3"}, elem: 2.0, target: true},
}
for _, test := range tests {
exists := Contains(test.elems, test.elem)
if exists != test.target {
t.Errorf("%v not exist %v", test.elems, test.elem)
}
}
}