2 Star 1 Fork 1

mosache/YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
slicex.go 1.35 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-11-17 11:55 . temp
package slicex
func SliceExclude[T comparable](source, exclude []T) []T {
r := make([]T, 0)
excludeMap := make(map[T]struct{})
for _, e := range exclude {
excludeMap[e] = struct{}{}
}
for _, e := range source {
if _, ok := excludeMap[e]; !ok {
r = append(r, e)
}
}
return r
}
func Unique[T comparable](source []T) []T {
r := make([]T, 0)
uniqueMap := make(map[T]struct{})
for _, e := range source {
if _, ok := uniqueMap[e]; !ok {
r = append(r, e)
uniqueMap[e] = struct{}{}
}
}
return r
}
func Contains[T comparable](source []T, target T) bool {
if len(source) == 0 {
return false
}
var r bool
for _, e := range source {
if e == target {
r = true
break
}
}
return r
}
func New[T any]() []T {
r := make([]T, 0)
return r
}
/*
GroupBy
将slice按照key分组
*/
func GroupBy[K comparable, V any, T []V](keyFunc func(V) K, source T) map[K]T {
m := make(map[K]T)
for _, e := range source {
key := keyFunc(e)
if _, ok := m[key]; ok {
m[key] = append(m[key], e)
} else {
m[key] = T{e}
}
}
return m
}
func Insert[T any](source []T, element T, index int) []T {
length := len(source)
if index > length {
panic("index out of range")
}
newSlice := make([]T, length+1)
newSlice[index] = element
copy(newSlice[:index], source[:index])
copy(newSlice[index+1:], source[index:])
return newSlice
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.58

搜索帮助