-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
61 lines (51 loc) · 1.68 KB
/
map.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
package slice
import (
"errors"
"github.com/golang-infrastructure/go-gtypes"
)
// ---------------------------------------------------------------------------------------------------------------------
// Map 对数组中的每个元素应用给定行为,并返回
func Map[T, V any](slice []T, mapFunc func(index int, item T) V) []V {
newSlice := make([]V, 0)
for index, item := range slice {
newSlice = append(newSlice, mapFunc(index, item))
}
return newSlice
}
func FlatMap[T, V any](slice []T, flatFunc func(index int, item T) []V) []V {
newSlice := make([]V, 0)
for index, item := range slice {
newSlice = append(newSlice, flatFunc(index, item)...)
}
return newSlice
}
// ---------------------------------------------------------------------------------------------------------------------
// AllAdd 切片中所有元素加上一个值
func AllAdd[T gtypes.Ordered](slice []T, n T) {
for index, item := range slice {
slice[index] = item + n
}
}
// AllSub 切片中所有元素减去一个值
func AllSub[T gtypes.Integer | gtypes.Float](slice []T, n T) {
for index, item := range slice {
slice[index] = item - n
}
}
// AllMulti 切片中所有元素乘以一个值
func AllMulti[T gtypes.Integer | gtypes.Float](slice []T, n T) {
for index, item := range slice {
slice[index] = item * n
}
}
// AllDivision 切片中所有元素除以一个值
func AllDivision[T gtypes.Integer | gtypes.Float](slice []T, n T) error {
if n == 0 {
return errors.New("can not division zero")
}
for index, item := range slice {
slice[index] = item / n
}
return nil
}
// ---------------------------------------------------------------------------------------------------------------------