From a619fd24f6f8bc0e053836bdfb3f5e533315a6fa Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Tue, 29 Oct 2024 20:06:09 -0400 Subject: [PATCH] Added map and reduce functions, and a function to return the difference between two sets --- misc.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/misc.go b/misc.go index 1206a57..4d2a5eb 100644 --- a/misc.go +++ b/misc.go @@ -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] +}