forked from samber/lo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind.go
116 lines (90 loc) · 2.27 KB
/
find.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
package lo
import (
"fmt"
"math"
)
// import "golang.org/x/exp/constraints"
// IndexOf returns the index at which the first occurrence of a value is found in an array or return -1
// if the value cannot be found.
func IndexOf[T comparable](collection []T, element T) int {
for i, item := range collection {
if item == element {
return i
}
}
return -1
}
// IndexOf returns the index at which the last occurrence of a value is found in an array or return -1
// if the value cannot be found.
func LastIndexOf[T comparable](collection []T, element T) int {
length := len(collection)
for i := length - 1; i >= 0; i-- {
if collection[i] == element {
return i
}
}
return -1
}
// Find search an element in a slice based on a predicate. It returns element and true if element was found.
func Find[T any](collection []T, predicate func(T) bool) (T, bool) {
for _, item := range collection {
if predicate(item) {
return item, true
}
}
var result T
return result, false
}
// Min search the minimum value of a collection.
func Min[T Ordered](collection []T) T {
var min T
for i := 0; i < len(collection); i++ {
item := collection[i]
if i == 0 {
min = item
continue
}
// if item.Less(min) {
if item < min {
min = item
}
}
return min
}
// Max search the maximum value of a collection.
func Max[T Ordered](collection []T) T {
var max T
for i := 0; i < len(collection); i++ {
item := collection[i]
if i == 0 {
max = item
continue
}
if item > max {
max = item
}
}
return max
}
// Last returns the last element of a collection or error if empty.
func Last[T any](collection []T) (T, error) {
length := len(collection)
if length == 0 {
var t T
return t, fmt.Errorf("last: cannot extract the last element of an empty slice")
}
return collection[length-1], nil
}
// Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element
// from the end is returned. An error is returned when nth is out of slice bounds.
func Nth[T any](collection []T, nth int) (T, error) {
if int(math.Abs(float64(nth))) > len(collection) {
var t T
return t, fmt.Errorf("nth: %d out of slice bounds", nth)
}
length := len(collection)
if nth >= 0 {
return collection[nth], nil
}
return collection[length+nth], nil
}