-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlists.go
More file actions
143 lines (128 loc) · 2.31 KB
/
lists.go
File metadata and controls
143 lines (128 loc) · 2.31 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package utils
func First[T any](list []T) *T {
if len(list) == 0 {
return nil
}
return &list[0]
}
func FirstFn[T any](list []T, fn func(T) bool) *T {
for _, t := range list {
if fn(t) {
return &t
}
}
return nil
}
func Single[T any](list []T) (*T, error) {
if len(list) == 1 {
return &list[0], nil
}
return nil, ErrNoSingleElement
}
func SingleFn[T any](list []T, fn func(T) bool) (*T, error) {
var single *T = nil
for _, t := range list {
if fn(t) {
if single == nil {
single = &t
} else {
return nil, ErrNoSingleElement
}
}
}
if single != nil {
return single, nil
}
return nil, ErrNoSingleElement
}
func Filter[T any](list []T, fn func(T) bool) []T {
result := make([]T, 0)
for _, t := range list {
if fn(t) {
result = append(result, t)
}
}
return result
}
func FilterNotNil[T any](list []*T) []*T {
result := make([]*T, 0)
for _, t := range list {
if t != nil {
result = append(result, t)
}
}
return result
}
func Map[T, R any](list []T, fn func(T) R) []R {
result := make([]R, 0, len(list))
for _, t := range list {
result = append(result, fn(t))
}
return result
}
func Any[T any](list []T, fn func(T) bool) bool {
for _, t := range list {
if fn(t) {
return true
}
}
return false
}
func All[T any](list []T, fn func(T) bool) bool {
for _, t := range list {
if !fn(t) {
return false
}
}
return true
}
func None[T any](list []T, fn func(T) bool) bool {
return !Any(list, fn)
}
func Distinct[T comparable](list []T) []T {
seen := make(map[T]struct{})
result := make([]T, 0)
for _, t := range list {
if _, ok := seen[t]; !ok {
seen[t] = struct{}{}
result = append(result, t)
}
}
return result
}
func ListEqual[T comparable](a, b []T) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func Count[T any](list []T, fn func(T) bool) int {
count := 0
for _, t := range list {
if fn(t) {
count++
}
}
return count
}
// Sum returns the sum of the elements in the list.
func Sum[T Number](list []T) T {
sum := T(0)
for _, t := range list {
sum += t
}
return sum
}
// SumBy returns the sum of the elements in the list mapped by fn.
func SumBy[T any, N Number](list []T, fn func(T) N) N {
sum := N(0)
for _, t := range list {
sum += fn(t)
}
return sum
}