github.com/df-mc/dragonfly@v0.9.13/server/internal/sliceutil/sliceutil.go (about)

     1  package sliceutil
     2  
     3  import "slices"
     4  
     5  // Convert converts a slice of type B to a slice of type A. Convert panics if B
     6  // cannot be type asserted to type A.
     7  func Convert[A, B any, S ~[]B](v S) []A {
     8  	a := make([]A, len(v))
     9  	for i, b := range v {
    10  		a[i] = (any)(b).(A)
    11  	}
    12  	return a
    13  }
    14  
    15  // Index returns the index of the first occurrence of v in s, or -1 if not
    16  // present. Index accepts any type, as opposed to slices.Index, but might panic
    17  // if E is not comparable.
    18  func Index[E any](s []E, v E) int {
    19  	for i, vs := range s {
    20  		if (any)(v) == (any)(vs) {
    21  			return i
    22  		}
    23  	}
    24  	return -1
    25  }
    26  
    27  // SearchValue iterates through slice v, calling function f for every element.
    28  // If true is returned in this function, the respective element is returned and
    29  // ok is true. If the function f does not return true for any element, false is
    30  // returned.
    31  func SearchValue[A any, S ~[]A](v S, f func(a A) bool) (a A, ok bool) {
    32  	for _, val := range v {
    33  		if f(val) {
    34  			return val, true
    35  		}
    36  	}
    37  	return
    38  }
    39  
    40  // Filter iterates over elements of collection, returning an array of all
    41  // elements function c returns true for.
    42  func Filter[E any](s []E, c func(E) bool) []E {
    43  	a := make([]E, 0, len(s))
    44  	for _, e := range s {
    45  		if c(e) {
    46  			a = append(a, e)
    47  		}
    48  	}
    49  	return a
    50  }
    51  
    52  // DeleteVal deletes the first occurrence of a value in a slice of the type E
    53  // and returns a new slice without the value.
    54  func DeleteVal[E any](s []E, v E) []E {
    55  	if i := Index(s, v); i != -1 {
    56  		return slices.Clone(slices.Delete(s, i, i+1))
    57  	}
    58  	return s
    59  }