Created
July 22, 2025 08:43
-
-
Save arshamalh/d5d3a33cb35091b59b1d83d9181e1abc to your computer and use it in GitHub Desktop.
Caped sorted insert for already sorted slices
This file contains hidden or 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
// 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