Add Substr and Split template functions

Both of these can take any type the cast lib can turn into a string.
This commit is contained in:
Xin Fan 2015-03-20 13:44:53 +11:00 committed by bep
parent 9cc3d67c57
commit 04817c7b83
2 changed files with 75 additions and 0 deletions

View file

@ -188,6 +188,22 @@ func compareGetFloat(a interface{}, b interface{}) (float64, float64) {
return left, right return left, right
} }
func Substr(a interface{}, pos, length int) (string, error) {
aStr, err := cast.ToStringE(a)
if err != nil {
return "", err
}
return aStr[pos:length], nil
}
func Split(a interface{}, delimiter string) ([]string, error) {
aStr, err := cast.ToStringE(a)
if err != nil {
return []string{}, err
}
return strings.Split(aStr, delimiter), nil
}
func Intersect(l1, l2 interface{}) (interface{}, error) { func Intersect(l1, l2 interface{}) (interface{}, error) {
if l1 == nil || l2 == nil { if l1 == nil || l2 == nil {
return make([]interface{}, 0), nil return make([]interface{}, 0), nil
@ -1308,6 +1324,8 @@ func init() {
"lt": Lt, "lt": Lt,
"le": Le, "le": Le,
"in": In, "in": In,
"substr": Substr,
"split": Split,
"intersect": Intersect, "intersect": Intersect,
"isSet": IsSet, "isSet": IsSet,
"isset": IsSet, "isset": IsSet,

View file

@ -276,6 +276,63 @@ func TestIn(t *testing.T) {
} }
} }
func TestSubstr(t *testing.T) {
for i, this := range []struct {
v1 interface{}
v2 int
v3 int
expect string
}{
{"abc", 1, 2, "b"},
{"abc", 1, 3, "bc"},
{"abc", 0, 1, "a"},
} {
result, err := Substr(this.v1, this.v2, this.v3)
if err != nil {
t.Errorf("[%d] failed: %s", i, err)
continue
}
if result != this.expect {
t.Errorf("[%d] Got %v but expected %v", i, result, this.expect)
}
}
_, err := Substr(tstNoStringer{}, 0, 1)
if err == nil {
t.Error("Expected error for non-string-convertable variable")
}
}
func TestSplit(t *testing.T) {
for i, this := range []struct {
v1 interface{}
v2 string
expect []string
}{
{"a, b", ", ", []string{"a", "b"}},
{"a & b & c", " & ", []string{"a", "b", "c"}},
{"http://exmaple.com", "http://", []string{"", "exmaple.com"}},
} {
result, err := Split(this.v1, this.v2)
if err != nil {
t.Errorf("[%d] failed: %s", i, err)
continue
}
if !reflect.DeepEqual(result, this.expect) {
t.Errorf("[%d] Got %s but expected %s", i, result, this.expect)
}
}
_, err := Split(tstNoStringer{}, ",")
if err == nil {
t.Error("Expected error for non-string-convertable variable")
}
}
func TestIntersect(t *testing.T) { func TestIntersect(t *testing.T) {
for i, this := range []struct { for i, this := range []struct {
sequence1 interface{} sequence1 interface{}