From 277cc1793f4a083dbb0f383613c84fab688a200b Mon Sep 17 00:00:00 2001 From: Reindert Vetter Date: Thu, 22 Dec 2022 23:31:51 +0100 Subject: [PATCH] Implement Join to collection --- support/collection.go | 28 ++++++++++++++++++++++++++++ support/test/collection_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/support/collection.go b/support/collection.go index a9aac0d..7121da2 100644 --- a/support/collection.go +++ b/support/collection.go @@ -5,6 +5,7 @@ import ( "github.com/spf13/cast" "reflect" "strconv" + "strings" ) type Collection []Value @@ -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 +} diff --git a/support/test/collection_test.go b/support/test/collection_test.go index 01a63f7..871ebfa 100644 --- a/support/test/collection_test.go +++ b/support/test/collection_test.go @@ -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{}