Skip to content

Instantly share code, notes, and snippets.

@karrick
Created October 19, 2017 18:29
Show Gist options
  • Save karrick/6584a7b663b65db8b6ff8ac8caa2ce1e to your computer and use it in GitHub Desktop.
Save karrick/6584a7b663b65db8b6ff8ac8caa2ce1e to your computer and use it in GitHub Desktop.
sortAndMaybeInsertString
package sortAndMaybeInsertString
func sortAndMaybeInsertString(s string, a []string) []string {
if len(a) == 0 {
return append(a, s)
}
sort.Strings(a)
i := sort.SearchStrings(a, s)
if i < len(a) && a[i] == s {
return a // return slice when string already present
}
// Without two copies and mandatory allocation, insert string into array at
// index.
a = append(a, a[len(a)-1])
copy(a[i+1:], a[i:len(a)-1])
a[i] = s
return a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment