Created
February 7, 2026 20:20
-
-
Save lionello/8f04af29cf54ae651a80b335ffd1058f to your computer and use it in GitHub Desktop.
GroupAdjacentFunc in Golang
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
| 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