github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/utils/dedup/dedup.go (about)

     1  package dedup
     2  
     3  import "sort"
     4  
     5  // SortAndDedupString takes a slice of strings, sorts it and then returns an
     6  // integer for the new size. The existing slice is modified however neither its
     7  // length nor capacity is altered. Hence the return value being an integer.
     8  // For example
     9  //
    10  //     s := []string{"a", "f", "f", "c", "g", "d", "a", "b", "e", "a", "b", "b"}
    11  //     i := dedup.SortAndDedupString(s)
    12  //     fmt.Println(s)     // [a b c d e f g d e f f g]
    13  //     fmt.Println(s[:i]) // [a b c d e f g]
    14  func SortAndDedupString(s []string) int {
    15  	if len(s) == 0 {
    16  		return 0
    17  	}
    18  
    19  	sort.Slice(s, func(i, j int) bool {
    20  		switch {
    21  		case len(s[i]) == 0:
    22  			return true
    23  
    24  		case len(s[j]) == 0:
    25  			return false
    26  
    27  		case s[i][0] == '-' && s[j][0] != '-':
    28  			return false
    29  
    30  		case s[i][0] != '-' && s[j][0] == '-':
    31  			return true
    32  
    33  		case len(s[i]) < len(s[j]):
    34  			for pos := range s[i] {
    35  				switch {
    36  				case s[i][pos] == ':':
    37  					return true
    38  				//case s[j][pos] == ':':
    39  				//	return false
    40  				case s[i][pos] == s[j][pos]:
    41  					continue
    42  				default:
    43  					return s[i][pos] < s[j][pos]
    44  				}
    45  			}
    46  			return true
    47  
    48  		case len(s[i]) > len(s[j]):
    49  			for pos := range s[j] {
    50  				switch {
    51  				//case s[i][pos] == ':':
    52  				//	return true
    53  				case s[j][pos] == ':':
    54  					return false
    55  				case s[i][pos] == s[j][pos]:
    56  					continue
    57  				default:
    58  					return s[i][pos] < s[j][pos]
    59  				}
    60  			}
    61  			return false
    62  
    63  		default:
    64  			for pos := range s[i] {
    65  				switch {
    66  				//case s[i][pos] == ':':
    67  				//	return true
    68  				//case s[j][pos] == ':':
    69  				//	return false
    70  				case s[i][pos] == s[j][pos]:
    71  					continue
    72  				default:
    73  					return s[i][pos] < s[j][pos]
    74  				}
    75  			}
    76  			return true
    77  		}
    78  	})
    79  
    80  	j := 1
    81  	for i := 0; i < len(s)-1; i++ {
    82  		if s[i] != s[i+1] {
    83  			s[j] = s[i+1]
    84  			j++
    85  		}
    86  	}
    87  
    88  	return j
    89  }