Skip to content

Commit

Permalink
chore: add copying slices.Sort() (#1884)
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas authored Jun 26, 2024
1 parent a3a6bc8 commit 928cf26
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions internal/slices/slices.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package slices

import (
"cmp"
"sort"
)

func Map[T, U any](slice []T, fn func(T) U) []U {
result := make([]U, len(slice))
for i, v := range slice {
Expand Down Expand Up @@ -61,6 +66,16 @@ func AppendOrReplace[T any](slice []T, value T, fn func(T) bool) []T {
return append(slice, value)
}

// Sort returns a sorted clone of slice.
func Sort[T cmp.Ordered](slice []T) []T {
out := make([]T, len(slice))
copy(out, slice)
sort.Slice(out, func(i, j int) bool {
return out[i] < out[j]
})
return out
}

func FlatMap[T, U any](slice []T, fn func(T) []U) []U {
result := make([]U, 0, len(slice))
for _, v := range slice {
Expand Down

0 comments on commit 928cf26

Please sign in to comment.