Skip to content

Instantly share code, notes, and snippets.

@lionello
Created February 7, 2026 20:20
Show Gist options
  • Select an option

  • Save lionello/8f04af29cf54ae651a80b335ffd1058f to your computer and use it in GitHub Desktop.

Select an option

Save lionello/8f04af29cf54ae651a80b335ffd1058f to your computer and use it in GitHub Desktop.
GroupAdjacentFunc in Golang
func GroupAdjacentFunc[T any, K comparable](seq iter.Seq[T], by func(item T) K) iter.Seq[[]T] {
return func(yield func([]T) bool) {
var group []T
var groupKey K
for item := range seq {
key := by(item)
if key == groupKey {
group = append(group, item)
} else {
if len(group) > 0 && !yield(group) {
return // stop iteration
}
group = []T{item}
groupKey = key
}
}
if len(group) > 0 {
_ = yield(group)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment