Files
sendico/api/pkg/mutil/reorder/reorder.go
Stephan D e77d1ab793 linting
2026-03-10 12:31:09 +01:00

43 lines
1.1 KiB
Go

package reorder
import (
"github.com/tech/sendico/pkg/merrors"
"github.com/tech/sendico/pkg/model"
)
// IndexableRefs reorders a slice of IndexableRef items
// Returns the reordered slice with updated indices, or an error if indices are invalid
func IndexableRefs(items []model.IndexableRef, oldIndex, newIndex int) ([]model.IndexableRef, error) {
// Find the item to reorder
targetIndex := -1
for i, item := range items {
if item.Index == oldIndex {
targetIndex = i
break
}
}
if targetIndex == -1 {
return nil, merrors.InvalidArgument("Item not found at specified index", "oldIndex")
}
// Validate new index bounds
if newIndex < 0 || newIndex >= len(items) {
return nil, merrors.InvalidArgument("Invalid new index for reorder", "newIndex")
}
// Remove the item from its current position
itemToMove := items[targetIndex]
items = append(items[:targetIndex], items[targetIndex+1:]...)
// Insert the item at the new position
items = append(items[:newIndex],
append([]model.IndexableRef{itemToMove}, items[newIndex:]...)...)
// Update indices
for i := range items {
items[i].Index = i
}
return items, nil
}