From b0d1d394520abe51973262c516151963f055c8b6 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 17 Jun 2022 17:01:37 +0800 Subject: [PATCH] feat: add IndexOf and LastIndexOf function in slice.go --- slice/slice.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index 5cfdf50..33b8efc 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -902,3 +902,31 @@ func Without(slice interface{}, values ...interface{}) interface{} { return res.Interface() } + +// IndexOf returns the index at which the first occurrence of a value is found in a slice or return -1 +// if the value cannot be found. +func IndexOf(slice, value interface{}) int { + sv := sliceValue(slice) + + for i := 0; i < sv.Len(); i++ { + if reflect.DeepEqual(sv.Index(i).Interface(), value) { + return i + } + } + + return -1 +} + +// LastIndexOf returns the index at which the last occurrence of a value is found in a slice or return -1 +// if the value cannot be found. +func LastIndexOf(slice, value interface{}) int { + sv := sliceValue(slice) + + for i := sv.Len() - 1; i > 0; i-- { + if reflect.DeepEqual(sv.Index(i).Interface(), value) { + return i + } + } + + return -1 +}