Skip to content

Commit

Permalink
Implement Join to collection
Browse files Browse the repository at this point in the history
  • Loading branch information
reindert-vetter committed Dec 22, 2022
1 parent 9e38fa6 commit 277cc17
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
28 changes: 28 additions & 0 deletions support/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/spf13/cast"
"reflect"
"strconv"
"strings"
)

type Collection []Value
Expand Down Expand Up @@ -209,3 +210,30 @@ func (c Collection) WhereE(key string, operator string, expected interface{}) (C
}
return result, err
}

// Join concatenates the elements of its first argument to create a single string. The separator
// string sep is placed between elements in the resulting string.
func (c Collection) Join(key string, sep string) string {
result, err := c.JoinE(key, sep)
if err != nil {
panic(err)
}
return result
}

// JoinE concatenates the elements of its first argument to create a single string. The separator
// string sep is placed between elements in the resulting string.
func (c Collection) JoinE(key string, sep string) (string, error) {
parts := []string{}
for _, value := range c {
part, err := value.Get(key).StringE()
if err != nil {
return "", err
}
parts = append(parts, part)
}

result := strings.Join(parts, sep)

return result, nil
}
28 changes: 28 additions & 0 deletions support/test/collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,32 @@ func Test_collection_where_slice_has_other_integer(t *testing.T) {
require.Equal(t, 1, len(result))
}

func Test_collection_join_one(t *testing.T) {
data := support.NewCollection([]map[string]interface{}{
{
"id": 32,
},
},
)

result := data.Join("id", ", ")

require.Equal(t, "32", result)
}

func Test_collection_join_multiple(t *testing.T) {
data := support.NewCollection([]map[string]interface{}{
{
"id": 32,
},
{
"id": 43,
},
})

result := data.Join("id", ", ")

require.Equal(t, "32, 43", result)
}

var emptyInterface interface{}

0 comments on commit 277cc17

Please sign in to comment.