commit d86519fe954cbeef88ccd1c96f611aeb908389d9
parent c4c0fd180a4b2b0c6986d61fa64f4fb2fbc40d24
Author: Yongbin Kim <iam@yongbin.kim>
Date: Thu, 29 Sep 2022 14:12:03 +0900
slices: feat: Added two select methods.
Select finds item from slice. It works like `Filter` function, but
instead of returning every matched item, it returns the first one.
SelectFirst finds from beginning of slice, SelectLast is from last.
Signed-off-by: Yongbin Kim <iam@yongbin.kim>
Diffstat:
1 file changed, 24 insertions(+), 0 deletions(-)
diff --git a/slices/select.go b/slices/select.go
@@ -0,0 +1,24 @@
+package slices
+
+// SelectFirst finds a item from beginning of slice and returns the first
+// matched item.
+func SelectFirst[T any](items []T, action func(T) bool) (result T, ok bool) {
+ for _, item := range items {
+ if action(item) {
+ return item, true
+ }
+ }
+ return
+}
+
+// SelectLast finds a item from ending of slice and returns the first
+// matched item.
+func SelectLast[T any](items []T, action func(T) bool) (result T, ok bool) {
+ for i := len(items) - 1; i >= 0; i-- {
+ item := items[i]
+ if action(item) {
+ return item, true
+ }
+ }
+ return
+}