[优化] 代码优化

This commit is contained in:
ryan
2026-05-31 20:02:01 +08:00
parent 4775e5cb73
commit 5612403d48
3 changed files with 31 additions and 48 deletions
+27
View File
@@ -1,5 +1,7 @@
package utils
import "strings"
// Unique returns a new slice containing only the unique elements of the input slice,
// preserving their original order.
func Unique[T comparable](slice []T) []T {
@@ -17,3 +19,28 @@ func Unique[T comparable](slice []T) []T {
}
return result
}
// UniqueAndCleanStringSlice trims spaces, removes empty elements, and returns only the unique elements
// of the input string slice. It preserves order and returns nil if the resulting slice is empty.
func UniqueAndCleanStringSlice(slice []string) []string {
if slice == nil {
return nil
}
seen := make(map[string]struct{})
result := make([]string, 0)
for _, item := range slice {
trimmed := strings.TrimSpace(item)
if trimmed == "" {
continue
}
if _, ok := seen[trimmed]; ok {
continue
}
seen[trimmed] = struct{}{}
result = append(result, trimmed)
}
if len(result) == 0 {
return nil
}
return result
}