diff --git a/README.md b/README.md index 545dcc8..c16fec0 100644 --- a/README.md +++ b/README.md @@ -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>) @@ -534,6 +535,16 @@ Reverse reverses the order of the elements in the slice a. Complexity: O\(len\(a\)\). +## func [ReverseCopy]() + +```go +func ReverseCopy[T any](a []T) []T +``` + +ReverseCopy returns a reversed copy of slice a. + +Complexity: O\(len\(a\)\). + ## func [Shuffle]() ```go diff --git a/transform.go b/transform.go index a7cd8c3..7014f88 100644 --- a/transform.go +++ b/transform.go @@ -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 +} diff --git a/transform_test.go b/transform_test.go index 855db0f..8cef326 100644 --- a/transform_test.go +++ b/transform_test.go @@ -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})) +}