Skip to content

Commit 1685ea1

Browse files
committed
add match_with operator
1 parent f7bc5f6 commit 1685ea1

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

querybuilder/operator/match_with.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package operator
2+
3+
import (
4+
"reflect"
5+
"regexp"
6+
"strings"
7+
)
8+
9+
func init() {
10+
AddOperator(MatchWith)
11+
}
12+
13+
var MatchWith = &Operator{
14+
Name: "match_with",
15+
Evaluate: func(input, value interface{}) bool {
16+
rv := reflect.ValueOf(value)
17+
if rv.Kind() != reflect.String {
18+
return false
19+
}
20+
21+
v := value.(string)
22+
in := input.(string)
23+
24+
if strings.HasPrefix(v, "/") && strings.HasSuffix(v, "/") {
25+
v = v[1 : len(v)-1] // remove slashes
26+
vr, err := regexp.Compile("(?i)" + v) // add ignore case option to regex and compile it
27+
if err != nil {
28+
return false
29+
}
30+
31+
if vr.MatchString(in) {
32+
return true
33+
}
34+
}
35+
36+
return false
37+
},
38+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package operator
2+
3+
import "testing"
4+
5+
func TestMatchWith(t *testing.T) {
6+
var inputs = []struct {
7+
title string
8+
value interface{}
9+
input interface{}
10+
want bool
11+
}{
12+
{title: "match-1", value: `/word\sto/`, input: "my word to match", want: true},
13+
{title: "match-2", value: `/word\sto/`, input: "My Word To Match", want: true},
14+
{title: "match-4", value: "word to", input: "my word to match", want: false},
15+
}
16+
17+
for _, input := range inputs {
18+
t.Run(input.title, func(t *testing.T) {
19+
got := MatchWith.Evaluate(input.input, input.value)
20+
if got != input.want {
21+
t.Errorf("%v match with %v got: %t, want: %t", input.input, input.value, got, input.want)
22+
}
23+
})
24+
}
25+
}

0 commit comments

Comments
 (0)