From 928cf26275b82865b3a730c438e9316ecc500b52 Mon Sep 17 00:00:00 2001 From: Alec Thomas Date: Thu, 27 Jun 2024 09:12:38 +1000 Subject: [PATCH] chore: add copying slices.Sort() (#1884) --- internal/slices/slices.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/internal/slices/slices.go b/internal/slices/slices.go index 85266a94fa..64b8816ccc 100644 --- a/internal/slices/slices.go +++ b/internal/slices/slices.go @@ -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 { @@ -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 {