From f11aa9f59af0b97b45055adb28358b8dd361cb37 Mon Sep 17 00:00:00 2001 From: "Viktor A. Rozenko Voitenko" Date: Fri, 22 Jul 2022 11:00:07 +0100 Subject: [PATCH] feat(CollectMap): allow flexible stream collection into builtin Go map --- hmap.go | 26 ++++++++++++++++++++++++++ hmap_test.go | 22 ++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 hmap.go create mode 100644 hmap_test.go diff --git a/hmap.go b/hmap.go new file mode 100644 index 0000000..5d39378 --- /dev/null +++ b/hmap.go @@ -0,0 +1,26 @@ +package fungi + +import "io" + +// CollectMap exhaustively collects items from a given stream into a builtin map +// type. As its first argument, it requires a function that knows how to take an +// item and split it into map Key and Value of appropriate type. +func CollectMap[ + T, V any, + K comparable, +](keyval func(T) (K, V)) StreamReducer[T, map[K]V] { + return func(items Stream[T]) (hmap map[K]V, err error) { + hmap = make(map[K]V) + var item T + for err == nil { + if item, err = items.Next(); err == nil { + key, value := keyval(item) + hmap[key] = value + } + } + if err == io.EOF { + err = nil + } + return + } +} diff --git a/hmap_test.go b/hmap_test.go new file mode 100644 index 0000000..4562629 --- /dev/null +++ b/hmap_test.go @@ -0,0 +1,22 @@ +package fungi + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCollectMap(t *testing.T) { + source := SliceStream([]int{1, 2, 3}) + result, err := CollectMap(duplicate)(source) + assert.NoError(t, err) + assert.Equal(t, map[int]int{ + 1: 1, + 2: 2, + 3: 3, + }, result) +} + +func duplicate(i int) (int, int) { + return i, i +}