From 470312936c7430ea463ef2b054f2fc6025c5ed7d Mon Sep 17 00:00:00 2001 From: xing Date: Tue, 17 Jan 2023 13:23:42 +0800 Subject: [PATCH] stream --- stream/simpleStream.go | 15 +++++++++++++++ stream/simpleStream_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/stream/simpleStream.go b/stream/simpleStream.go index b62d42a..c65c495 100644 --- a/stream/simpleStream.go +++ b/stream/simpleStream.go @@ -31,6 +31,21 @@ func SimpleParallelFilterAndMapToMap[K comparable, V any, T any](a SimpleSliceSt return } +func SimpleSliceFilterAndMapToMap[K comparable, V any, T any](a SimpleSliceStream[T], fn func(t T) (K, V, bool), isCoverPrev bool) (r SimpleMapStream[K, V]) { + m := make(map[K]V) + a.ForEach(func(t T) { + k, v, ok := fn(t) + if ok { + _, ok = m[k] + if isCoverPrev || !ok { + m[k] = v + } + } + }) + r.m = m + return +} + func SimpleStreamFilterAndMap[R, T any](a SimpleSliceStream[T], fn func(T) (R, bool)) SimpleSliceStream[R] { return NewSimpleSliceStream(helper.SliceFilterAndMap(a.arr, fn)) } diff --git a/stream/simpleStream_test.go b/stream/simpleStream_test.go index e761a92..c1502d0 100644 --- a/stream/simpleStream_test.go +++ b/stream/simpleStream_test.go @@ -560,3 +560,40 @@ func TestSimpleParallelFilterAndMapToMap(t *testing.T) { }) } } + +func TestSimpleSliceFilterAndMapToMap(t *testing.T) { + type args[T int, K int, V int] struct { + a SimpleSliceStream[T] + fn func(t T) (K, V, bool) + isCoverPrev bool + } + type testCase[T int, K int, V int] struct { + name string + args args[T, K, V] + wantR SimpleMapStream[K, V] + } + tests := []testCase[int, int, int]{ + { + name: "t1", + args: args[int, int, int]{ + a: NewSimpleSliceStream(helper.RangeSlice(1, 10, 1)), + fn: func(i int) (int, int, bool) { + if i > 6 { + return i, i, true + } + return 0, 0, false + }, + }, + wantR: NewSimpleMapStream(helper.SliceToMap(helper.RangeSlice(7, 10, 1), func(t int) (int, int) { + return t, t + }, true)), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if gotR := SimpleSliceFilterAndMapToMap(tt.args.a, tt.args.fn, tt.args.isCoverPrev); !reflect.DeepEqual(gotR, tt.wantR) { + t.Errorf("SimpleSliceFilterAndMapToMap() = %v, want %v", gotR, tt.wantR) + } + }) + } +}