Share occurrence duplicate grouping bookkeeping
This commit is contained in:
37
internal/modules/dnd/shared/duplicates.go
Normal file
37
internal/modules/dnd/shared/duplicates.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package shared
|
||||
|
||||
// DuplicatePositions identifies a retained representative and later duplicates
|
||||
// by their positions in the caller's input sequence.
|
||||
type DuplicatePositions struct {
|
||||
Representative int
|
||||
Removed []int
|
||||
}
|
||||
|
||||
// GroupDuplicates retains the first eligible record per key; ineligible records
|
||||
// remain independent. Duplicate groups follow representative encounter order.
|
||||
func GroupDuplicates[K comparable](count int, keyFor func(int) (K, bool)) ([]int, []DuplicatePositions) {
|
||||
retained := make([]int, 0, count)
|
||||
groups := make([]DuplicatePositions, 0)
|
||||
byKey := make(map[K]int)
|
||||
for index := 0; index < count; index++ {
|
||||
key, eligible := keyFor(index)
|
||||
if !eligible {
|
||||
retained = append(retained, index)
|
||||
continue
|
||||
}
|
||||
if group, exists := byKey[key]; exists {
|
||||
groups[group].Removed = append(groups[group].Removed, index)
|
||||
continue
|
||||
}
|
||||
byKey[key] = len(groups)
|
||||
groups = append(groups, DuplicatePositions{Representative: index})
|
||||
retained = append(retained, index)
|
||||
}
|
||||
var duplicates []DuplicatePositions
|
||||
for _, group := range groups {
|
||||
if len(group.Removed) > 0 {
|
||||
duplicates = append(duplicates, group)
|
||||
}
|
||||
}
|
||||
return retained, duplicates
|
||||
}
|
||||
21
internal/modules/dnd/shared/duplicates_test.go
Normal file
21
internal/modules/dnd/shared/duplicates_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGroupDuplicatesKeepsIneligibleAndRepresentativeOrder(t *testing.T) {
|
||||
keys := []string{"a", "b", "invalid", "b", "invalid", "a", "c"}
|
||||
retained, groups := GroupDuplicates(len(keys), func(index int) (string, bool) { return keys[index], keys[index] != "invalid" })
|
||||
if want := []int{0, 1, 2, 4, 6}; !reflect.DeepEqual(retained, want) {
|
||||
t.Fatalf("retained = %v, want %v", retained, want)
|
||||
}
|
||||
if want := []DuplicatePositions{{Representative: 0, Removed: []int{5}}, {Representative: 1, Removed: []int{3}}}; !reflect.DeepEqual(groups, want) {
|
||||
t.Fatalf("groups = %#v, want %#v", groups, want)
|
||||
}
|
||||
retained, groups = GroupDuplicates(0, func(int) (string, bool) { t.Fatal("unexpected callback"); return "", false })
|
||||
if retained == nil || len(retained) != 0 || len(groups) != 0 {
|
||||
t.Fatalf("empty result = %#v, %#v", retained, groups)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user