Change to variadic int args in Slicestr

Makes for a better template api.
This commit is contained in:
bep 2015-03-23 19:18:17 +01:00
parent 5b0245ca59
commit be84f93716
2 changed files with 23 additions and 21 deletions

View file

@ -190,22 +190,23 @@ func compareGetFloat(a interface{}, b interface{}) (float64, float64) {
// Slicing in Slicestr is done by specifying a half-open range with // Slicing in Slicestr is done by specifying a half-open range with
// two indices, start and end. 1 and 4 creates a slice including elements 1 through 3. // two indices, start and end. 1 and 4 creates a slice including elements 1 through 3.
// The start and/or end indices can be omitted by setting one or both of them to -1; // The end index can be omitted, it defaults to the string's length.
// they default to zero and the slice's length respectively func Slicestr(a interface{}, startEnd ...int) (string, error) {
func Slicestr(a interface{}, start, end int) (string, error) {
aStr, err := cast.ToStringE(a) aStr, err := cast.ToStringE(a)
if err != nil { if err != nil {
return "", err return "", err
} }
if start != -1 && end != -1 { if len(startEnd) > 2 {
return aStr[start:end], nil return "", errors.New("too many arguments")
} else if start == -1 && end == -1 { }
return aStr[:], nil
} else if start == -1 { if len(startEnd) == 2 {
return aStr[:end], nil return aStr[startEnd[0]:startEnd[1]], nil
} else if len(startEnd) == 1 {
return aStr[startEnd[0]:], nil
} else { } else {
return aStr[start:], nil return aStr[:], nil
} }
} }

View file

@ -279,20 +279,21 @@ func TestIn(t *testing.T) {
func TestSlicestr(t *testing.T) { func TestSlicestr(t *testing.T) {
for i, this := range []struct { for i, this := range []struct {
v1 interface{} v1 interface{}
v2 int v2 []int
v3 int
expect interface{} expect interface{}
}{ }{
{"abc", 1, 2, "b"}, {"abc", []int{1, 2}, "b"},
{"abc", 1, 3, "bc"}, {"abc", []int{1, 3}, "bc"},
{"abc", 0, 1, "a"}, {"abc", []int{0, 1}, "a"},
{"abcdef", -1, -1, "abcdef"}, {"abcdef", []int{}, "abcdef"},
{"abcdef", -1, 2, "ab"}, {"abcdef", []int{0, 6}, "abcdef"},
{"abcdef", 2, -1, "cdef"}, {"abcdef", []int{0, 2}, "ab"},
{123, 1, 3, "23"}, {"abcdef", []int{2}, "cdef"},
{tstNoStringer{}, 0, 1, false}, {123, []int{1, 3}, "23"},
{123, []int{1, 2, 3}, false},
{tstNoStringer{}, []int{0, 1}, false},
} { } {
result, err := Slicestr(this.v1, this.v2, this.v3) result, err := Slicestr(this.v1, this.v2...)
if b, ok := this.expect.(bool); ok && !b { if b, ok := this.expect.(bool); ok && !b {
if err == nil { if err == nil {