Skip to content

Commit

Permalink
feat(slice): add Reverse (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofnds authored May 6, 2023
1 parent f1b8b27 commit beaa34b
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
5 changes: 5 additions & 0 deletions slice/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down
42 changes: 42 additions & 0 deletions slice/collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions tests/benchmark/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}

0 comments on commit beaa34b

Please sign in to comment.