Skip to content

Commit

Permalink
#65: Add ArrayReverse (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman authored Aug 12, 2022
1 parent 515deda commit 1398dff
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}
}
52 changes: 52 additions & 0 deletions array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
}

0 comments on commit 1398dff

Please sign in to comment.