|
|
|
@ -52,3 +52,39 @@ func allEqual[T comparable](items ...T) bool {
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Returns all elements in slice A that are NOT in slice B
|
|
|
|
|
func setDifference[T comparable](s1 []T, s2 []T) []T {
|
|
|
|
|
toReturn := make([]T, 0)
|
|
|
|
|
for _, val := range s1 {
|
|
|
|
|
if !slices.Contains(s2, val) {
|
|
|
|
|
toReturn = append(toReturn, val)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return toReturn
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Map function - convert a slice of T to a slice of V, based on a function
|
|
|
|
|
// that maps a T to a V
|
|
|
|
|
func Map[T, V any](slc []T, fn func(T) V) []V {
|
|
|
|
|
toReturn := make([]V, len(slc))
|
|
|
|
|
for i, val := range slc {
|
|
|
|
|
toReturn[i] = fn(val)
|
|
|
|
|
}
|
|
|
|
|
return toReturn
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Reduce function - reduces a slice of a type into a value of the type,
|
|
|
|
|
// based on the given function.
|
|
|
|
|
func Reduce[T any](slc []T, fn func(T, T) T) T {
|
|
|
|
|
if len(slc) == 0 {
|
|
|
|
|
panic("Reduce on empty slice.")
|
|
|
|
|
}
|
|
|
|
|
for len(slc) > 1 {
|
|
|
|
|
v1 := slc[0]
|
|
|
|
|
v2 := slc[1]
|
|
|
|
|
slc = slc[1:]
|
|
|
|
|
slc[0] = fn(v1, v2)
|
|
|
|
|
}
|
|
|
|
|
return slc[0]
|
|
|
|
|
}
|
|
|
|
|