...

Source file src/k8s.io/kubernetes/pkg/util/slice/slice.go

Documentation: k8s.io/kubernetes/pkg/util/slice

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

View as plain text