goyave.dev/goyave/v4@v4.4.11/util/sliceutil/sliceutil.go (about)

     1  package sliceutil
     2  
     3  import "reflect"
     4  
     5  // IndexOf get the index of the given value in the given slice,
     6  // or -1 if not found.
     7  func IndexOf(slice interface{}, value interface{}) int {
     8  	list := reflect.ValueOf(slice)
     9  	length := list.Len()
    10  	for i := 0; i < length; i++ {
    11  		if list.Index(i).Interface() == value {
    12  			return i
    13  		}
    14  	}
    15  	return -1
    16  }
    17  
    18  // Contains check if a slice contains a value.
    19  func Contains(slice interface{}, value interface{}) bool {
    20  	return IndexOf(slice, value) != -1
    21  }
    22  
    23  // IndexOfStr get the index of the given value in the given string slice,
    24  // or -1 if not found.
    25  // Prefer using this function instead of IndexOf for better performance.
    26  func IndexOfStr(slice []string, value string) int {
    27  	for i, v := range slice {
    28  		if v == value {
    29  			return i
    30  		}
    31  	}
    32  	return -1
    33  }
    34  
    35  // ContainsStr check if a string slice contains a value.
    36  // Prefer using this function instead of Contains for better performance.
    37  func ContainsStr(slice []string, value string) bool {
    38  	return IndexOfStr(slice, value) != -1
    39  }
    40  
    41  // Equal check if two generic slices are the same.
    42  func Equal(first interface{}, second interface{}) bool {
    43  	l1 := reflect.ValueOf(first)
    44  	l2 := reflect.ValueOf(second)
    45  	length := l1.Len()
    46  	if length != l2.Len() {
    47  		return false
    48  	}
    49  
    50  	for i := 0; i < length; i++ {
    51  		if l1.Index(i).Interface() != l2.Index(i).Interface() {
    52  			return false
    53  		}
    54  	}
    55  	return true
    56  }