github.com/verrazzano/verrazzano@v1.7.0/pkg/string/comma_separated.go (about)

     1  // Copyright (C) 2021, 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 "strings"
     7  
     8  // CommaSeparatedStringContains checks for a string in a comma separated list of strings
     9  // commaSeparated is the comma separated string to search. May be nil.
    10  // s is the string to search for.
    11  // Returns true if the string is found and false otherwise.
    12  func CommaSeparatedStringContains(commaSeparated string, s string) bool {
    13  	split := strings.Split(commaSeparated, ",")
    14  	found := false
    15  	for _, ac := range split {
    16  		if ac == s {
    17  			found = true
    18  			break
    19  		}
    20  	}
    21  	return found
    22  }
    23  
    24  // AppendToCommaSeparatedString appends a string to a comma separated list.
    25  // It first checks that the entry is not already part of the comma separated list.
    26  // commaSeparated is the comma separated string to append into. May be empty.
    27  // s is the string to add.
    28  // Returns the updated comma separated string
    29  func AppendToCommaSeparatedString(commaSeparated string, s string) string {
    30  	// If the string is empty, return the value passed in
    31  	if commaSeparated == "" {
    32  		return s
    33  	}
    34  
    35  	// Check if the value is already contained in the comma separated list
    36  	if CommaSeparatedStringContains(commaSeparated, s) {
    37  		return commaSeparated
    38  	}
    39  
    40  	// Append the new value
    41  	split := strings.Split(commaSeparated, ",")
    42  	split = append(split, s)
    43  	return strings.Join(split, ",")
    44  }
    45  
    46  // RemoveFromCommaSeparatedString removes a string from a comma separated list.
    47  // It first checks that the entry is not already part of the comma separated list.
    48  // commaSeparated is the comma separated list to remove from. May be empty.
    49  // s is the string to remove.
    50  // Returns the updated comma separated string
    51  func RemoveFromCommaSeparatedString(commaSeparated string, s string) string {
    52  	// If the string is empty, return the value passed in
    53  	if commaSeparated == "" {
    54  		return commaSeparated
    55  	}
    56  
    57  	// Check if the value is not contained in the comma separated list
    58  	if !CommaSeparatedStringContains(commaSeparated, s) {
    59  		return commaSeparated
    60  	}
    61  
    62  	// Remove the value
    63  	split := strings.Split(commaSeparated, ",")
    64  	split = RemoveStringFromSlice(split, s)
    65  	return strings.Join(split, ",")
    66  }