Skip to content

Commit

Permalink
feat(CollectMap): allow flexible stream collection into builtin Go map
Browse files Browse the repository at this point in the history
  • Loading branch information
sharpvik committed Jul 22, 2022
1 parent 7c7aaab commit f11aa9f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
26 changes: 26 additions & 0 deletions hmap.go
Original file line number Diff line number Diff line change
@@ -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
}
}
22 changes: 22 additions & 0 deletions hmap_test.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit f11aa9f

Please sign in to comment.