-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
119 lines (98 loc) · 2.38 KB
/
slice.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
package utils
func Chunk[T any](slice []T, size int) [][]T {
var chunks [][]T
for i := 0; i < len(slice); i += size {
end := i + size
if end > len(slice) {
end = len(slice)
}
chunks = append(chunks, slice[i:end])
}
return chunks
}
func Reverse[T any](slice []T) []T {
buf := make([]T, len(slice))
begin := 0
end := len(slice) - 1
for begin < end {
buf[begin] = slice[end]
buf[end] = slice[begin]
begin++
end--
}
return buf
}
func Reduce[T any](slice []T, reducer func(T, T, int) T, accumulator T) T {
result := accumulator
for key, val := range slice {
result = reducer(result, val, key)
}
return result
}
func Map[T any](slice []T, mapper func(T) T) []T {
result := make([]T, len(slice))
for i, val := range slice {
result[i] = mapper(val)
}
return result
}
func Filter[T any](slice []T, predicate func(T) bool) []T {
var result []T
for _, val := range slice {
if predicate(val) {
result = append(result, val)
}
}
return result
}
func PadEnd[T any](slice []T, targetLength int, padValue T) []T {
currentLength := len(slice)
paddingLength := targetLength - currentLength
if paddingLength <= 0 || currentLength > targetLength {
return slice
}
newSlice := make([]T, 0, paddingLength)
for i := 0; i < paddingLength; i++ {
newSlice = append(newSlice, padValue)
}
newSlice = append(slice, newSlice...)
return newSlice
}
func PadEndString(val string, length int, padValue string) string {
currentLength := len(val)
paddingLength := length - currentLength
if paddingLength <= 0 || currentLength > length {
return val
}
pad := ""
for i := 0; i < paddingLength; i++ {
pad = pad + padValue
}
return val + pad
}
func PadStart[T any](slice []T, targetLength int, padValue T) []T {
currentLength := len(slice)
paddingLength := targetLength - currentLength
if paddingLength <= 0 || currentLength > targetLength {
return slice
}
newSlice := make([]T, 0, paddingLength)
for i := 0; i < paddingLength; i++ {
newSlice = append(newSlice, padValue)
}
newSlice = append(newSlice, slice...)
return newSlice
}
func GroupBy[T any, K comparable](slice []T, getKey func(T) K) map[K][]T {
groups := make(map[K][]T)
for _, item := range slice {
key := getKey(item)
groups[key] = append(groups[key], item)
}
return groups
}
func ForEach[T any](slice []T, callback func(value T, key int)) {
for k, v := range slice {
callback(v, k)
}
}