-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(CollectMap): allow flexible stream collection into builtin Go map
- Loading branch information
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |