Skip to content

Commit beaa34b

Browse files
authored
feat(slice): add Reverse (#96)
1 parent f1b8b27 commit beaa34b

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

slice/collection.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ func (c Collection[V]) Each(f func(i int, v V)) Collection[V] {
8282
return c
8383
}
8484

85+
// Reverse reverses the collection
86+
func (c Collection[V]) Reverse() Collection[V] {
87+
return collections.Reverse(c)
88+
}
89+
8590
// Sort passes the collection and the given params to the generic Sort function and
8691
// returns the collection.
8792
func (c Collection[V]) Sort(f func(current, next V) bool) Collection[V] {

slice/collection_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,48 @@ func TestTap(t *testing.T) {
267267
t.Errorf("expected returned collection to equal %v. got %v", sut, c)
268268
}
269269
}
270+
func TestReversingTwiceYieldsTheSameCollection(t *testing.T) {
271+
coll := Collect(1, 2, 3, 4, 5)
272+
reversedTwice := coll.Copy().Reverse().Reverse()
273+
274+
if !reflect.DeepEqual(coll, reversedTwice) {
275+
t.Errorf("expected %v, got %v", coll, reversedTwice)
276+
}
277+
}
278+
279+
func TestReverse(t *testing.T) {
280+
testCases := []struct {
281+
description string
282+
input Collection[int]
283+
expected Collection[int]
284+
}{
285+
{
286+
"reversing empty collection",
287+
Collection[int]{},
288+
Collection[int]{},
289+
},
290+
{
291+
"reversing collection with a single element",
292+
Collection[int]{1},
293+
Collection[int]{1},
294+
},
295+
{
296+
"reversing a collection with 10 elements",
297+
Collection[int]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
298+
Collection[int]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1},
299+
},
300+
}
301+
302+
for _, tc := range testCases {
303+
t.Run(tc.description, func(t *testing.T) {
304+
got := tc.input.Reverse()
305+
306+
if !reflect.DeepEqual(tc.expected, got) {
307+
t.Errorf("expected %v, got %v", tc.expected, got)
308+
}
309+
})
310+
}
311+
}
270312

271313
func TestSearch(t *testing.T) {
272314
testCases := []struct {

tests/benchmark/slice/slice_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ func BenchmarkCollectionSlicePut(b *testing.B) {
3939
sliceCollection = sliceCollection.Put(sliceCollection.Count()/2, n)
4040
}
4141
}
42+
43+
func BenchmarkSliceCollectionReverse(b *testing.B) {
44+
for n := 0; n < b.N; n++ {
45+
sliceCollection = sliceCollection.Reverse()
46+
}
47+
}

0 commit comments

Comments
 (0)