slice.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package slice provides utility methods for common operations on slices.
  14. package slice
  15. import (
  16. "sort"
  17. )
  18. // CopyStrings copies the contents of the specified string slice
  19. // into a new slice.
  20. func CopyStrings(s []string) []string {
  21. if s == nil {
  22. return nil
  23. }
  24. c := make([]string, len(s))
  25. copy(c, s)
  26. return c
  27. }
  28. // SortStrings sorts the specified string slice in place. It returns the same
  29. // slice that was provided in order to facilitate method chaining.
  30. func SortStrings(s []string) []string {
  31. sort.Strings(s)
  32. return s
  33. }
  34. // ContainsString checks if a given slice of strings contains the provided string.
  35. // If a modifier func is provided, it is called with the slice item before the comparation.
  36. func ContainsString(slice []string, s string, modifier func(s string) string) bool {
  37. for _, item := range slice {
  38. if item == s {
  39. return true
  40. }
  41. if modifier != nil && modifier(item) == s {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // RemoveString returns a newly created []string that contains all items from slice that
  48. // are not equal to s and modifier(s) in case modifier func is provided.
  49. func RemoveString(slice []string, s string, modifier func(s string) string) []string {
  50. newSlice := make([]string, 0)
  51. for _, item := range slice {
  52. if item == s {
  53. continue
  54. }
  55. if modifier != nil && modifier(item) == s {
  56. continue
  57. }
  58. newSlice = append(newSlice, item)
  59. }
  60. if len(newSlice) == 0 {
  61. // Sanitize for unit tests so we don't need to distinguish empty array
  62. // and nil.
  63. newSlice = nil
  64. }
  65. return newSlice
  66. }