-
Notifications
You must be signed in to change notification settings - Fork 0
/
slices.go
124 lines (108 loc) · 2.35 KB
/
slices.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package slices
type Slice[T any] []T
func (slice Slice[T]) Len() int { return len(slice) }
func (slice Slice[T]) ForEach(fn func(T)) {
for _, t := range slice {
fn(t)
}
}
func (slice Slice[T]) Filter(fn func(T) bool) []T {
var newSlices []T
for _, t := range slice {
if fn(t) {
newSlices = append(newSlices, t)
}
}
return newSlices
}
func (slice Slice[T]) Every(fn func(T) bool) bool {
for _, t := range slice {
if !fn(t) {
return false
}
}
return true
}
func (slice Slice[T]) Some(fn func(T) bool) bool {
for _, t := range slice {
if fn(t) {
return true
}
}
return false
}
func (slice Slice[T]) Zip(s []T) [][2]T {
var newSlice [][2]T
for i := range slice {
newSlice = append(newSlice, [2]T{slice[i], s[i]})
}
return newSlice
}
func (slice Slice[T]) Reduce(fn func(T, T) T) T {
ret := fn(slice[0], slice[1])
for i := 2; i < len(slice); i++ {
ret = fn(ret, slice[i])
}
return ret
}
type MapSlice[T, V any] Slice[T]
func (slice MapSlice[T, V]) Map(fn func(T) V) []V {
ret := make([]V, 0, len(slice))
for _, s := range slice {
ret = append(ret, fn(s))
}
return ret
}
// 学学kotlin的定义
type Array[S, T any] []S
//type Function[T any] func[T]()
func (a Array[S, T]) Map(fn func(S) T) []T {
ret := make([]T, 0, len(a))
for _, s := range a {
ret = append(ret, fn(s))
}
return ret
}
type ComparableSlice[T comparable] []T
// 去重
func (slices ComparableSlice[T]) Deduplicate() ComparableSlice[T] {
if len(slices) < SmallArrayLen {
newslices := make(ComparableSlice[T], 0, 2)
for i := 0; i < len(slices); i++ {
if !In(slices[i], newslices) {
newslices = append(newslices, slices[i])
}
}
return newslices
}
set := make(map[T]struct{})
for i := 0; i < len(slices); i++ {
set[slices[i]] = struct{}{}
}
newslices := make(ComparableSlice[T], 0, len(slices))
for k := range set {
newslices = append(newslices, k)
}
return newslices
}
// 去重
func Deduplicate[S ~[]T, T comparable](slice S) S {
if len(slice) < SmallArrayLen {
newslice := make(S, 0, 2)
for i := 0; i < len(slice); i++ {
if !In(slice[i], newslice) {
newslice = append(newslice, slice[i])
}
}
return newslice
}
set := make(map[T]struct{})
for i := 0; i < len(slice); i++ {
set[slice[i]] = struct{}{}
}
newslice := make(S, 0, len(slice))
for k := range set {
newslice = append(newslice, k)
}
return newslice
}