-
Notifications
You must be signed in to change notification settings - Fork 1
/
generics.go
66 lines (55 loc) · 1.25 KB
/
generics.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 utility
// get the index of a certain item in a string slice
func IndexOf[T comparable](target T, data []T) int {
for index, value := range data {
if target == value {
return index
}
}
return -1
}
// check whether a certain item exists in a string slice
func SliceContains[T comparable](target T, data []T) bool {
for _, v := range data {
if v == target {
return true
}
}
return false
}
// get the first predicate match of the slice
//
// returns nil if none of the items match
func GetFirstMatch[T any](arr []T, predicate func(T, int) bool) *T {
for i, value := range arr {
if predicate(value, i) {
return &value
}
}
return nil
}
// returns a new slice containing all the items on which the predicate returns true
func Filter[T any](arr []T, predicate func(T, int) bool) []T {
newArr := []T{}
for i, item := range arr {
if predicate(item, i) {
newArr = append(newArr, item)
}
}
return newArr
}
func Map[T any, N any](arr []T, predicate func(T, int) N) []N {
newArr := []N{}
for i, item := range arr {
newArr = append(newArr, predicate(item, i))
}
return newArr
}
func Some[T any](arr []T, predicate func(T, int) bool) bool {
for i, item := range arr {
if predicate(item, i) {
return true
}
}
return false
}