From beaa34b79184e07658661c9f5bb706a6733af9fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Fernandes?= <9938253+joaofnds@users.noreply.github.com> Date: Sat, 6 May 2023 14:54:52 -0300 Subject: [PATCH] feat(slice): add `Reverse` (#96) --- slice/collection.go | 5 ++++ slice/collection_test.go | 42 +++++++++++++++++++++++++++++ tests/benchmark/slice/slice_test.go | 6 +++++ 3 files changed, 53 insertions(+) diff --git a/slice/collection.go b/slice/collection.go index 9e0fff2..5ed9573 100644 --- a/slice/collection.go +++ b/slice/collection.go @@ -82,6 +82,11 @@ func (c Collection[V]) Each(f func(i int, v V)) Collection[V] { return c } +// Reverse reverses the collection +func (c Collection[V]) Reverse() Collection[V] { + return collections.Reverse(c) +} + // Sort passes the collection and the given params to the generic Sort function and // returns the collection. func (c Collection[V]) Sort(f func(current, next V) bool) Collection[V] { diff --git a/slice/collection_test.go b/slice/collection_test.go index 76f0160..ec14726 100644 --- a/slice/collection_test.go +++ b/slice/collection_test.go @@ -267,6 +267,48 @@ func TestTap(t *testing.T) { t.Errorf("expected returned collection to equal %v. got %v", sut, c) } } +func TestReversingTwiceYieldsTheSameCollection(t *testing.T) { + coll := Collect(1, 2, 3, 4, 5) + reversedTwice := coll.Copy().Reverse().Reverse() + + if !reflect.DeepEqual(coll, reversedTwice) { + t.Errorf("expected %v, got %v", coll, reversedTwice) + } +} + +func TestReverse(t *testing.T) { + testCases := []struct { + description string + input Collection[int] + expected Collection[int] + }{ + { + "reversing empty collection", + Collection[int]{}, + Collection[int]{}, + }, + { + "reversing collection with a single element", + Collection[int]{1}, + Collection[int]{1}, + }, + { + "reversing a collection with 10 elements", + Collection[int]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + Collection[int]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, + }, + } + + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + got := tc.input.Reverse() + + if !reflect.DeepEqual(tc.expected, got) { + t.Errorf("expected %v, got %v", tc.expected, got) + } + }) + } +} func TestSearch(t *testing.T) { testCases := []struct { diff --git a/tests/benchmark/slice/slice_test.go b/tests/benchmark/slice/slice_test.go index 65f0752..90d5cef 100644 --- a/tests/benchmark/slice/slice_test.go +++ b/tests/benchmark/slice/slice_test.go @@ -39,3 +39,9 @@ func BenchmarkCollectionSlicePut(b *testing.B) { sliceCollection = sliceCollection.Put(sliceCollection.Count()/2, n) } } + +func BenchmarkSliceCollectionReverse(b *testing.B) { + for n := 0; n < b.N; n++ { + sliceCollection = sliceCollection.Reverse() + } +}