Sonically/slice_utils.go

60 lines
1.1 KiB
Go

package main
// Slice Utils instead of ArrayList
// Returns Index of T
func SliceIndexOf[T comparable](slc []T, el T) int {
for i, x := range slc {
if x == el {
return i
}
}
return -1
}
// Swap T1 and T2 at indexes
func SliceSwapAtIndexes[T comparable](slc []T, el int, el2 int) {
x := slc[el]
slc[el] = slc[el2]
slc[el2] = x
}
// Returns true if Slice contains T
func SliceContains[T comparable](slc []T, el T) bool {
for _, x := range slc {
if x == el {
return true
}
}
return false
}
// Remove T if exists
func SliceRemove[T comparable](slc []T, el T) []T {
res := SliceIndexOf(slc, el)
if res != -1 {
return SliceRemoveAt(slc, res)
}
return slc
}
func SliceRemoveAt[T comparable](slc []T, el int) []T {
for i := el; i <= len(slc)-2; i++ {
slc[i] = slc[i+1]
}
// x:= (len(slc)-2)
// slc = append([]T(nil), slc[:x]...)
return slc[:(len(slc) - 1)]
}
func SliceInsertAt[T comparable](slc []T, el T, pos int) {
slc = append(slc, slc[len(slc)-1])
for i := len(slc) - 2; i > pos; i-- {
slc[i] = slc[i-1]
}
}
func SliceClear[T comparable](slc []T) []T {
return []T{}
}