-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
66 lines (53 loc) · 1.04 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
package goslices
func All[S ~[]T, T any](arr S, fn PredicateFn[T]) bool {
for _, el := range arr {
if !fn(el) {
return false
}
}
return true
}
func Any[S ~[]T, T any](arr S, fn PredicateFn[T]) bool {
for _, el := range arr {
if fn(el) {
return true
}
}
return false
}
func Each[S ~[]T, T any](arr S, fn func(T)) {
for _, el := range arr {
fn(el)
}
}
func Filter[S ~[]T, T any](arr S, fn PredicateFn[T]) S {
result := make(S, 0, len(arr))
for _, el := range arr {
if fn(el) {
result = append(result, el)
}
}
return result
}
func Find[S ~[]T, T any](arr S, fn PredicateFn[T]) (T, error) {
for _, el := range arr {
if fn(el) {
return el, nil
}
}
var tmp T
return tmp, ErrNotFound
}
func Map[S ~[]T, T any, U any](arr S, fn MapFn[T, U]) []U {
result := make([]U, 0, len(arr))
for _, el := range arr {
result = append(result, fn(el))
}
return result
}
func Reduce[S ~[]T, T any, U any](arr S, fn AccumulatorFn[T, U], initial U) U {
for _, el := range arr {
initial = fn(initial, el)
}
return initial
}