3
0

Updates expr function count

- It returns count based on params
- count(foo) counts all elements
- count(foo, 'bar', 'baz') counts number of bars and bazs in foo
This commit is contained in:
Vivek Patel
2021-09-08 08:33:41 +05:30
parent 2acaa0062e
commit 2cf27a1666
2 changed files with 50 additions and 6 deletions

View File

@@ -2,9 +2,9 @@ package expr
import (
"fmt"
"reflect"
"github.com/PaesslerAG/gval"
"reflect"
"strings"
)
func ArrayFunctions() []gval.Language {
@@ -94,15 +94,29 @@ func shift(arr interface{}) (out interface{}, err error) {
return c.Index(0).Interface(), nil
}
// count gets the count of occurrences in the slice
// count gets the count of occurrences in the first params(can be string, slice)
// If given only one parameter then it returns length as count
func count(arr interface{}, v ...interface{}) (count int, err error) {
var (
occ int
c = reflect.ValueOf(arr)
)
if len(v) == 0 {
return c.Len(), nil
}
if c.Kind() == reflect.String {
for _, ww := range v {
count += strings.Count(c.String(), reflect.ValueOf(ww).String())
}
return
}
if arr, err = toSlice(arr); err != nil {
return
}
var (
occ int
)
for _, vv := range v {
if occ, err = find(arr, vv); err != nil {
return 0, err

View File

@@ -264,6 +264,36 @@ func Test_count(t *testing.T) {
val: []interface{}{0.1, 1.1},
expect: 0,
},
{
arr: "foo",
val: nil,
expect: 3,
},
{
arr: "foo",
val: []interface{}{},
expect: 3,
},
{
arr: "foo bar",
val: []interface{}{},
expect: 7,
},
{
arr: []bool{true, true},
val: []interface{}{},
expect: 2,
},
{
arr: "foo",
val: []interface{}{"bar", "baz"},
expect: 0,
},
{
arr: "foo",
val: []interface{}{"o", 12},
expect: 2,
},
}
for p, tc := range tcc {