Skip to content

Commit

Permalink
Fix group with correct group order
Browse files Browse the repository at this point in the history
  • Loading branch information
ledongthuc committed Jan 3, 2022
1 parent 33f384b commit 5e872bf
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion group.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ package goterators

// Group groups elements into the nested level. Use a build-group function to define group type.
func Group[T any, G comparable](source []T, buildGroup func(item T) G) [][]T {
groupOrder := make([]G, 0, len(source))
m := map[G][]T{}
for index, item := range source {
group := buildGroup(item)
_, existed := m[group]
if !existed {
groupOrder = append(groupOrder, group)
}
m[group] = append(m[group], source[index])
}

output := make([][]T, 0, len(m))
for key := range m {
for _, key := range groupOrder {
output = append(output, m[key])
}
return output
Expand Down

0 comments on commit 5e872bf

Please sign in to comment.