index.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package help
  2. // IndexOf searches for an element that matches the conditions defined by a specified predicate
  3. // and returns the zero-based index of the first occurrence within the collection. This method
  4. // returns -1 if an item that matches the conditions is not found.
  5. func (q Query) IndexOf(predicate func(interface{}) bool) int {
  6. index := 0
  7. next := q.Iterate()
  8. for item, ok := next(); ok; item, ok = next() {
  9. if predicate(item) {
  10. return index
  11. }
  12. index++
  13. }
  14. return -1
  15. }
  16. // IndexOfT is the typed version of IndexOf.
  17. //
  18. // - predicateFn is of type "func(int,TSource)bool"
  19. //
  20. // NOTE: IndexOf has better performance than IndexOfT.
  21. func (q Query) IndexOfT(predicateFn interface{}) int {
  22. predicateGenericFunc, err := newGenericFunc(
  23. "IndexOfT", "predicateFn", predicateFn,
  24. simpleParamValidator(newElemTypeSlice(new(genericType)), newElemTypeSlice(new(bool))),
  25. )
  26. if err != nil {
  27. panic(err)
  28. }
  29. predicateFunc := func(item interface{}) bool {
  30. return predicateGenericFunc.Call(item).(bool)
  31. }
  32. return q.IndexOf(predicateFunc)
  33. }