-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfirst.go
More file actions
33 lines (29 loc) · 813 Bytes
/
first.go
File metadata and controls
33 lines (29 loc) · 813 Bytes
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
package underscore
import "errors"
// ErrEmptySlice is returned when trying to get the first element of an empty slice
var ErrEmptySlice = errors.New("underscore: empty slice")
// First returns the first element of the slice.
// Returns an error if the slice is empty.
func First[T any](values []T) (T, error) {
var zero T
if len(values) == 0 {
return zero, ErrEmptySlice
}
return values[0], nil
}
// FirstN returns the first n elements of the slice.
// If n is greater than the slice length, returns the entire slice.
// If n is less than or equal to 0, returns an empty slice.
func FirstN[T any](values []T, n int) []T {
if n <= 0 {
return []T{}
}
if n >= len(values) {
res := make([]T, len(values))
copy(res, values)
return res
}
res := make([]T, n)
copy(res, values[:n])
return res
}