github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/slice.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  // SliceContains returns true if elt is in slice, panics if slice is not of Kind reflect.Slice
     9  func SliceContains(slice, elt interface{}) bool {
    10  	if slice == nil {
    11  		return false
    12  	}
    13  	v := reflect.ValueOf(slice)
    14  	if v.Kind() != reflect.Slice {
    15  		panic(fmt.Sprintf("Cannot call SliceContains on a non-slice %#v of kind %#v", slice, v.Kind().String()))
    16  	}
    17  	for i := 0; i < v.Len(); i++ {
    18  		if reflect.DeepEqual(v.Index(i).Interface(), elt) {
    19  			return true
    20  		}
    21  	}
    22  	return false
    23  }
    24  
    25  // StringSliceIntersection returns the intersecting elements of slices a and b.
    26  func StringSliceIntersection(a, b []string) []string {
    27  	inA := map[string]bool{}
    28  	out := []string{}
    29  	for _, elem := range a {
    30  		inA[elem] = true
    31  	}
    32  	for _, elem := range b {
    33  		if inA[elem] {
    34  			out = append(out, elem)
    35  		}
    36  	}
    37  	return out
    38  }
    39  
    40  // UniqueStrings takes a slice of strings and returns a new slice with duplicates removed.
    41  // Order is preserved.
    42  func UniqueStrings(slice []string) []string {
    43  	seen := map[string]bool{}
    44  	out := []string{}
    45  	for _, s := range slice {
    46  		if seen[s] {
    47  			continue
    48  		}
    49  		seen[s] = true
    50  		out = append(out, s)
    51  	}
    52  	return out
    53  }