Files
lo/docs/data/core-earliestbyerr.md
T
Samuel Berthe fa095e4b4f fix(doc): fix go playground demo URL (#832)
* fix(doc): fix go playground demo URL

* fix(doc): add more go playground demo URL
2026-03-06 00:09:59 +01:00

1.3 KiB

name, slug, sourceRef, category, subCategory, playUrl, variantHelpers, similarHelpers, position, signatures
name slug sourceRef category subCategory playUrl variantHelpers similarHelpers position signatures
EarliestByErr earliestbyerr find.go#L484 core find https://go.dev/play/p/zJUBUj7ANvq
core#find#earliestbyerr
core#find#earliestby
core#find#latestby
core#find#earliest
core#find#latest
core#find#minby
core#find#maxby
191
func EarliestByErr[T any](collection []T, iteratee func(item T) (time.Time, error)) (T, error)

Searches a collection for the element with the minimum time extracted by the predicate. Returns zero value and nil error when the collection is empty.

If the iteratee returns an error, iteration stops and the error is returned.

type Event struct{ At time.Time }
events := []Event{{At: time.Now().Add(2 * time.Hour)}, {At: time.Now()}}
first, err := lo.EarliestByErr(events, func(e Event) (time.Time, error) {
    return e.At, nil
})
// Event, <nil>

Example with error:

type Event struct{ At time.Time }
events := []Event{{At: time.Now()}, {At: time.Now().Add(time.Hour)}}
first, err := lo.EarliestByErr(events, func(e Event) (time.Time, error) {
    if e.At.After(time.Now().Add(30 * time.Minute)) {
        return time.Time{}, fmt.Errorf("event too far in the future")
    }
    return e.At, nil
})
// Event, error("event too far in the future")