github.com/verrazzano/verrazzano@v1.7.0/pkg/string/slice.go (about) 1 // Copyright (C) 2021, 2022, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package string 5 6 import ( 7 "sort" 8 ) 9 10 // SliceContainsString checks for a string in a slice of strings 11 // slice is the string slice to search. May be nil. 12 // s is the string to search for in the slice. 13 // Returns true if the string is found in the slice and false otherwise. 14 func SliceContainsString(slice []string, s string) bool { 15 for _, item := range slice { 16 if item == s { 17 return true 18 } 19 } 20 return false 21 } 22 23 // RemoveStringFromSlice removes a string from a string slice. 24 // slice is the string slice to remove the string from. May be nil. 25 // s is the string to remove from the slice. 26 // Returns a new slice with the remove string removed. 27 func RemoveStringFromSlice(slice []string, s string) []string { 28 result := []string{} 29 for _, item := range slice { 30 if item == s { 31 continue 32 } 33 result = append(result, item) 34 } 35 return result 36 } 37 38 // UnorderedEqual checks if a map and array have the same string elements. 39 // The same order is not required. 40 func UnorderedEqual(mapBool map[string]bool, arrayStr []string) bool { 41 if len(mapBool) != len(arrayStr) { 42 return false 43 } 44 for element := range mapBool { 45 if !SliceContainsString(arrayStr, element) { 46 return false 47 } 48 } 49 return true 50 } 51 52 // SliceToSet converts a slice of strings to a set of strings 53 func SliceToSet(list []string) map[string]bool { 54 outSet := make(map[string]bool) 55 for _, f := range list { 56 outSet[f] = true 57 } 58 return outSet 59 } 60 61 // SliceAddString Adds a string to a slice if it is not already present 62 func SliceAddString(slice []string, s string) ([]string, bool) { 63 if !SliceContainsString(slice, s) { 64 return append(slice, s), true 65 } 66 return slice, false 67 } 68 69 // compareSlices compares 2 string slices after sorting 70 func AreSlicesEqualWithoutOrder(slice1 []string, slice2 []string) bool { 71 s1 := make([]string, len(slice1)) 72 s2 := make([]string, len(slice2)) 73 copy(s1, slice1) 74 copy(s2, slice2) 75 76 if len(s1) != len(s2) { 77 return false 78 } 79 80 sort.Strings(s1) 81 sort.Strings(s2) 82 83 for i, v := range s1 { 84 if v != s2[i] { 85 return false 86 } 87 } 88 return true 89 }