Skip to content

Commit e507890

Browse files
committed
fn: add Last helper function
1 parent d8d5087 commit e507890

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

fn/func.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,20 @@ func First[T any](xs []*T, pred func(*T) bool) (*T, error) {
172172

173173
return nil, fmt.Errorf("no item found")
174174
}
175+
176+
// Last returns the last item in the slice that matches the predicate, or an
177+
// error if none matches.
178+
func Last[T any](xs []*T, pred func(*T) bool) (*T, error) {
179+
var matches []*T
180+
for i := range xs {
181+
if pred(xs[i]) {
182+
matches = append(matches, xs[i])
183+
}
184+
}
185+
186+
if len(matches) == 0 {
187+
return nil, fmt.Errorf("no item found")
188+
}
189+
190+
return matches[len(matches)-1], nil
191+
}

0 commit comments

Comments
 (0)