Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Created July 22, 2025 08:43
Show Gist options
  • Save arshamalh/d5d3a33cb35091b59b1d83d9181e1abc to your computer and use it in GitHub Desktop.
Save arshamalh/d5d3a33cb35091b59b1d83d9181e1abc to your computer and use it in GitHub Desktop.
Caped sorted insert for already sorted slices
// Inserts new item to a sorted list by still keeping it sorted and keeping the length to at most "max" elements.
func CapedSortedInsert[T any](items []T, item T, max int, cmpValue func(a, b T) int) []T {
insertionIndex := len(items)
for i, val := range items {
if cmpValue(item, val) == 1 {
insertionIndex = i
break
}
}
items = slices.Insert(items, insertionIndex, item)
if len(items) > max {
return items[:max]
}
return items
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment