Last active
March 20, 2021 02:33
-
-
Save NeoyeElf/6c9e0d28d4b4f3000f72b19fb9180e1e to your computer and use it in GitHub Desktop.
move slice elements to certain position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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