Skip to content

Commit 45c42f1

Browse files
committed
fix(collect): from slice and map even if stream is nil
1 parent dcd5294 commit 45c42f1

4 files changed

Lines changed: 27 additions & 17 deletions

File tree

filter_map.go

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,28 +33,13 @@ func FilterMap[I, O any](carry func(I) (O, bool)) StreamTransformer[I, O] {
3333
_, ok = carry(item)
3434
return
3535
})
36+
3637
mapper := Map(func(item I) (mapped O) {
3738
mapped, _ = carry(item)
3839
return
3940
})
41+
4042
return func(items Stream[I]) Stream[O] {
4143
return mapper(filter(items))
4244
}
4345
}
44-
45-
type filterMap[I, O any] struct {
46-
source Stream[I]
47-
carry func(I) (O, bool)
48-
}
49-
50-
func (t *filterMap[I, O]) Next() (item O, err error) {
51-
for {
52-
var origin I
53-
if origin, err = t.source.Next(); err != nil {
54-
return
55-
}
56-
if item, ok := t.carry(origin); ok {
57-
return item, nil
58-
}
59-
}
60-
}

hmap.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,23 @@ func CollectMap[
1111
](keyval func(T) (K, V)) StreamReducer[T, map[K]V] {
1212
return func(items Stream[T]) (hmap map[K]V, err error) {
1313
hmap = make(map[K]V)
14+
15+
if items == nil {
16+
return
17+
}
18+
1419
var item T
1520
for err == nil {
1621
if item, err = items.Next(); err == nil {
1722
key, value := keyval(item)
1823
hmap[key] = value
1924
}
2025
}
26+
2127
if err == io.EOF {
2228
err = nil
2329
}
30+
2431
return
2532
}
2633
}

slice.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,21 @@ func SliceStream[T any](items []T) Stream[T] {
1313
// end of this operation, io.EOF is not reported as this function is expected to
1414
// read stream until the end anyways.
1515
func CollectSlice[T any](items Stream[T]) (collected []T, err error) {
16+
if items == nil {
17+
return
18+
}
19+
1620
var item T
1721
for err == nil {
1822
if item, err = items.Next(); err == nil {
1923
collected = append(collected, item)
2024
}
2125
}
26+
2227
if err == io.EOF {
2328
err = nil
2429
}
30+
2531
return
2632
}
2733

slice_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package fungi
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestCollectSlice(t *testing.T) {
10+
_, err := CollectSlice[int](nil)
11+
assert.NoError(t, err)
12+
}

0 commit comments

Comments
 (0)