-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove.go
68 lines (56 loc) · 1.81 KB
/
remove.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package slice
// ------------------------------------------------ ---------------------------------------------------------------------
// Remove 移除slice中的元素,其实就是把原切片复制了一遍,复杂度是O(n)
func Remove[T comparable](slice []T, removeItem T) []T {
return Filter[T](slice, func(index int, item T) bool {
return item != removeItem
})
}
func Removes[T comparable](slice []T, removeItems ...T) []T {
return Filter[T](slice, func(index int, item T) bool {
return Contains(removeItems, item)
})
}
// ------------------------------------------------ ---------------------------------------------------------------------
// RemoveByIndex 根据下标删除元素,其实就是把元素复制了一遍,复杂度是O(n)
func RemoveByIndex[T any](slice []T, deleteIndex int) []T {
return Filter[T](slice, func(index int, item T) bool {
return index != deleteIndex
})
}
func RemoveByIndexes[T any](slice []T, deleteIndexes ...int) []T {
if len(deleteIndexes) == 0 {
return slice
}
set := ToSet(deleteIndexes)
return Filter[T](slice, func(index int, item T) bool {
_, exists := set[index]
return !exists
})
}
// ------------------------------------------------ ---------------------------------------------------------------------
func RemoveFirst[T any](slice []T) []T {
if len(slice) <= 1 {
return nil
}
return slice[1:]
}
func RemoveFirstN[T any](slice []T, n int) []T {
if len(slice) <= n {
return nil
}
return slice[n:]
}
func RemoveLast[T any](slice []T) []T {
if len(slice) <= 1 {
return nil
}
return slice[0 : len(slice)-1]
}
func RemoveLastN[T any](slice []T, n int) []T {
if len(slice) <= n {
return nil
}
return slice[0 : len(slice)-n]
}
// ------------------------------------------------ ---------------------------------------------------------------------