Skip to content

Instantly share code, notes, and snippets.

@adityajoshi12
Created June 24, 2022 07:42
Show Gist options
  • Save adityajoshi12/528160a4386c8f9d942933ca0310b713 to your computer and use it in GitHub Desktop.
Save adityajoshi12/528160a4386c8f9d942933ca0310b713 to your computer and use it in GitHub Desktop.
Golang slice utility functions
//Intersection returns the lists of all the elements that are common to both slices.
func Intersection(a, b interface{}) []interface{} {
set := make([]interface{}, 0)
hash := make(map[interface{}]bool)
av := reflect.ValueOf(a)
bv := reflect.ValueOf(b)
for i := 0; i < av.Len(); i++ {
el := av.Index(i).Interface()
hash[el] = true
}
for i := 0; i < bv.Len(); i++ {
el := bv.Index(i).Interface()
if _, found := hash[el]; found {
set = append(set, el)
}
}
return set
}
// Difference returns the lists of all the elements that are in superset but that are not present in subset.
func Difference(superset, subset interface{}) []interface{} {
set := make([]interface{}, 0)
hash := make(map[interface{}]bool)
av := reflect.ValueOf(superset)
bv := reflect.ValueOf(subset)
for i := 0; i < bv.Len(); i++ {
el := bv.Index(i).Interface()
hash[el] = true
}
for i := 0; i < av.Len(); i++ {
el := av.Index(i).Interface()
if _, found := hash[el]; !found {
set = append(set, el)
}
}
return set
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment