- common/tools 工具模块,10 个子功能:md5/cryptox/uuid/random/timex/convertx/strx/slicex/ip/filex(薄封装 GoFrame 内置组件) - AGENTS.md 项目智能体说明书(架构、规范、命令、记忆体系索引) - docs/change-log/2026-08-24.md 本次请求与变更记录 - .gitignore 排除 .workbuddy/;PROJECT_STRUCTURE.md 补充目录树
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
// Package slicex provides generic slice utilities built on the standard
|
|
// library (Go 1.23+).
|
|
package slicex
|
|
|
|
import (
|
|
"slices"
|
|
)
|
|
|
|
// Contains reports whether v is present in items.
|
|
func Contains[T comparable](items []T, v T) bool {
|
|
return slices.Contains(items, v)
|
|
}
|
|
|
|
// Unique returns items with duplicates removed, preserving first-seen order.
|
|
func Unique[T comparable](items []T) []T {
|
|
seen := make(map[T]struct{}, len(items))
|
|
out := make([]T, 0, len(items))
|
|
for _, v := range items {
|
|
if _, ok := seen[v]; ok {
|
|
continue
|
|
}
|
|
seen[v] = struct{}{}
|
|
out = append(out, v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Chunk splits items into sub-slices of at most size elements.
|
|
// Returns nil when size <= 0 or items is empty.
|
|
func Chunk[T any](items []T, size int) [][]T {
|
|
if size <= 0 || len(items) == 0 {
|
|
return nil
|
|
}
|
|
out := make([][]T, 0, (len(items)+size-1)/size)
|
|
for len(items) > 0 {
|
|
n := size
|
|
if len(items) < n {
|
|
n = len(items)
|
|
}
|
|
out = append(out, items[:n])
|
|
items = items[n:]
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Map applies fn to every element and returns the results.
|
|
func Map[T, R any](items []T, fn func(T) R) []R {
|
|
out := make([]R, len(items))
|
|
for i, v := range items {
|
|
out[i] = fn(v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Filter returns the elements for which fn returns true, preserving order.
|
|
func Filter[T any](items []T, fn func(T) bool) []T {
|
|
out := make([]T, 0, len(items))
|
|
for _, v := range items {
|
|
if fn(v) {
|
|
out = append(out, v)
|
|
}
|
|
}
|
|
return out
|
|
}
|