Skip to content

Instantly share code, notes, and snippets.

@NeoyeElf
Last active March 20, 2021 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeoyeElf/6c9e0d28d4b4f3000f72b19fb9180e1e to your computer and use it in GitHub Desktop.
Save NeoyeElf/6c9e0d28d4b4f3000f72b19fb9180e1e to your computer and use it in GitHub Desktop.
move slice elements to certain position
func sliceToMap(slice []string) map[string]interface{} {
res := make(map[string]interface{}, len(slice))
for _, v := range slice {
res[v] = nil
}
return res
}
// move elements to the front of the element at index i of the slice
// if i >= len(originSlice), means move the elements to the end of slice
func MoveElementsToPosition(originSlice []string, elements []string, position int) []string {
if position < 0 {
return originSlice
}
elementsMap := sliceToMap(elements)
newSlice := make([]string, len(originSlice))
i := 0
for idx, guid := range originSlice {
if idx == position {
for _, v := range elements {
newSlice[i] = v
i++
}
newSlice[i] = guid
i++
continue
}
if _, ok := elementsMap[guid]; ok {
continue
}
newSlice[i] = guid
i++
}
if position >= len(originSlice) {
for _, v := range elements {
newSlice[i] = v
i++
}
}
return newSlice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment