Skip to content

Commit

Permalink
Add ReverseCopy (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
chen3feng authored Aug 6, 2022
1 parent cb69a29 commit 0e0556b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Package stl4go is a generic container and algorithm library for go.
- [func RemoveIf[T any](a []T, cond func(T) bool) []T](<#func-removeif>)
- [func RemoveIfCopy[T any](a []T, cond func(T) bool) []T](<#func-removeifcopy>)
- [func Reverse[T any](a []T)](<#func-reverse>)
- [func ReverseCopy[T any](a []T) []T](<#func-reversecopy>)
- [func Shuffle[T any](a []T)](<#func-shuffle>)
- [func Sort[T Ordered](a []T)](<#func-sort>)
- [func SortFunc[T any](a []T, less func(x, y T) bool)](<#func-sortfunc>)
Expand Down Expand Up @@ -534,6 +535,16 @@ Reverse reverses the order of the elements in the slice a.

Complexity: O\(len\(a\)\).

## func [ReverseCopy](<https://github.com/chen3feng/stl4go/blob/master/transform.go#L167>)

```go
func ReverseCopy[T any](a []T) []T
```

ReverseCopy returns a reversed copy of slice a.

Complexity: O\(len\(a\)\).

## func [Shuffle](<https://github.com/chen3feng/stl4go/blob/master/transform.go#L149>)

```go
Expand Down
11 changes: 11 additions & 0 deletions transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,14 @@ func Reverse[T any](a []T) {
a[i], a[j] = a[j], a[i]
}
}

// ReverseCopy returns a reversed copy of slice a.
//
// Complexity: O(len(a)).
func ReverseCopy[T any](a []T) []T {
b := make([]T, 0, len(a))
for i := len(a) - 1; i >= 0; i-- {
b = append(b, a[i])
}
return b
}
6 changes: 6 additions & 0 deletions transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,9 @@ func Test_Reverse_Odd(t *testing.T) {
Reverse(a)
expectTrue(t, Equal(a, []int{5, 4, 3, 2, 1}))
}

func Test_ReverseCopy(t *testing.T) {
a := []int{1, 2, 3, 4, 5}
b := ReverseCopy(a)
expectTrue(t, Equal(b, []int{5, 4, 3, 2, 1}))
}

0 comments on commit 0e0556b

Please sign in to comment.