Skip to content

Commit

Permalink
slice, conv
Browse files Browse the repository at this point in the history
  • Loading branch information
esafonov committed Nov 25, 2023
1 parent 8c3d635 commit e9b3bcf
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
16 changes: 16 additions & 0 deletions collections/slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -712,3 +712,19 @@ func MergeSorted[T any](s1 []T, s2 []T, less func(v1, v2 T) bool, limit int) []T

return dst
}

// Sort slices ascending.
func Sort[T constraints.Ordered](s []T) {
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

// Sort slices descending.
func SortDesc[T constraints.Ordered](s []T) {
sort.Slice(s, func(i, j int) bool { return s[i] > s[j] })
}

// FitIndex fits the index into slice range.
// If the slice is empty the result will be -1.
func FitIndex[T any](index int, s []T) int {
return math.MustBetween(index, 0, len(s)-1)
}
13 changes: 13 additions & 0 deletions collections/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -879,3 +879,16 @@ func ExampleHasDuplicatesFunc() {
// false
// false
}

func ExampleFitIndex() {
fmt.Println(FitIndex(-1, []int{1, 1, 1}))
fmt.Println(FitIndex(11, []int{1, 1, 1}))
fmt.Println(FitIndex(1, []int{1, 1, 1}))
fmt.Println(FitIndex(1, []int{}))

// Output:
// 0
// 2
// 1
// -1
}
2 changes: 1 addition & 1 deletion conv/conv.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package unsafe
package conv

import (
"fmt"
Expand Down
2 changes: 1 addition & 1 deletion conv/conv_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package unsafe
package conv

import (
"fmt"
Expand Down

0 comments on commit e9b3bcf

Please sign in to comment.