Skip to content

Commit 8295318

Browse files
committed
add contains operator
1 parent 1685ea1 commit 8295318

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

querybuilder/operator/contains.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package operator
2+
3+
import (
4+
"reflect"
5+
"strings"
6+
)
7+
8+
func init() {
9+
AddOperator(Contains)
10+
}
11+
12+
var Contains = &Operator{
13+
Name: "contains",
14+
Evaluate: func(input, value interface{}) bool {
15+
rinput := reflect.ValueOf(input)
16+
17+
switch rinput.Kind() {
18+
case reflect.String:
19+
if strings.Contains(input.(string), value.(string)) {
20+
return true
21+
}
22+
case reflect.Slice:
23+
for i := 0; i < rinput.Len(); i++ {
24+
if rinput.Index(i).Interface() == value {
25+
return true
26+
}
27+
}
28+
default:
29+
return false
30+
}
31+
32+
return false
33+
},
34+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package operator
2+
3+
import "testing"
4+
5+
func TestContains(t *testing.T) {
6+
var inputs = []struct {
7+
title string
8+
value interface{}
9+
input interface{}
10+
want bool
11+
}{
12+
{title: "contains-1", value: "word to", input: "my word to match", want: true},
13+
{title: "contains-2", value: "my", input: "my word to match", want: true},
14+
{title: "contains-3", value: "myword", input: "my word to match", want: false},
15+
{title: "contains-4", value: 2, input: []int{1, 2, 3}, want: true},
16+
{title: "contains-5", value: 2.5, input: []float64{2.0, 2.3, 2.5, 3}, want: true},
17+
{title: "contains-6", value: "c", input: []string{"a", "b", "c"}, want: true},
18+
{title: "contains-7", value: "d", input: []string{"a", "b", "c"}, want: false},
19+
}
20+
21+
for _, input := range inputs {
22+
t.Run(input.title, func(t *testing.T) {
23+
got := Contains.Evaluate(input.input, input.value)
24+
if got != input.want {
25+
t.Errorf("%v contains %v got: %t, want: %t", input.input, input.value, got, input.want)
26+
}
27+
})
28+
}
29+
}

0 commit comments

Comments
 (0)