diff --git a/README.md b/README.md index 852ce16..46fab45 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Go library for PHP community with convenient functions * [ArrayMin/ArrayMax](#user-content-arrayminarraymax) * [ArrayUnique](#user-content-arrayunique) * [ArrayValues](#user-content-arrayvalues) + * [ArrayReverse](#user-content-arrayreverse) * [Range](#user-content-range) * [EqualSlices](#user-content-equalslices) * [Collections](#user-content-collections) @@ -386,6 +387,16 @@ res = pgo.ArrayValues(map[string]int{"a": 1, "b": 2, "c": 3}) // []int{1, 2, 3} res = pgo.ArrayValues(map[int]float64{1: 123.33, 2: 22, 3: 123.33}) // []float64{22, 123.33, 123.33} ``` +### ArrayReverse + +reverse slice passed as an argument + +```go +toReverse := []int{-3, 0, 4, 9, 13} +pgo.ArrayReverse(toReverse) +fmt.Println(toReverse) // []int{13, 9, 4, 0, -3} +``` + #### Range creates an int slice of min to max range diff --git a/array.go b/array.go index 0596469..d74df55 100644 --- a/array.go +++ b/array.go @@ -352,3 +352,10 @@ func ArrayValues[K, V comparable](a map[K]V) []V { return s } + +// ArrayReverse reverse slice passed as an argument +func ArrayReverse[V comparable](s []V) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} diff --git a/array_test.go b/array_test.go index 71bc1a4..5c45fba 100644 --- a/array_test.go +++ b/array_test.go @@ -530,3 +530,55 @@ func TestArrayValues(t *testing.T) { assert.Equal(t, res, v.res) } } + +func TestArrayReverse(t *testing.T) { + testInts := map[string]struct { + toReverse []int + reversed []int + }{ + "ok ints": { + toReverse: []int{-3, 0, 4, 9, 13}, + reversed: []int{13, 9, 4, 0, -3}, + }, + "ok empty ints": { + toReverse: []int{}, + reversed: []int{}, + }, + "ok one ints": { + toReverse: []int{}, + reversed: []int{}, + }, + } + + for n, tt := range testInts { + t.Run(n, func(t *testing.T) { + pgo.ArrayReverse(tt.toReverse) + assert.Equal(t, tt.toReverse, tt.reversed) + }) + } + + testStr := map[string]struct { + toReverse []string + reversed []string + }{ + "ok strings": { + toReverse: []string{"foo", "bar", "baz", "ipsum"}, + reversed: []string{"ipsum", "baz", "bar", "foo"}, + }, + "ok empty strings": { + toReverse: []string{}, + reversed: []string{}, + }, + "ok one string": { + toReverse: []string{"bark"}, + reversed: []string{"bark"}, + }, + } + + for n, tt := range testStr { + t.Run(n, func(t *testing.T) { + pgo.ArrayReverse(tt.toReverse) + assert.Equal(t, tt.toReverse, tt.reversed) + }) + } +}