Skip to content

Commit

Permalink
[TASK] TRK-4289 Add UniqueWithKeyBuilder function to gofp (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
hsequeda authored Jan 30, 2025
1 parent a05669c commit 3019266
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
15 changes: 15 additions & 0 deletions gofp/unique.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,18 @@ func IsUnique[T comparable](el []T) bool {

return true
}

// IsUniqueWithKeyBuilder checks if all elements in a slice after being transformed by the KeyBuilder function.
func IsUniqueWithKeyBuilder[T any, C comparable](el []T, kb KeyBuilder[T, C]) bool {
seen := make(Set[C])
for _, t := range el {
k := kb(t)
if seen.Has(k) {
return false
}

seen.Add(k)
}

return true
}
63 changes: 63 additions & 0 deletions gofp/unique_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,36 @@ func TestIsUnique_String(t *testing.T) {
}
}

func TestIsUniqueWithKeyBuilder(t *testing.T) {
type data struct {
foo string
bar []int
}
type test struct {
name string
d []data
want bool
}
tests := []test{
{
name: "unique",
d: []data{{foo: "m"}, {foo: "x", bar: []int{1}}, {foo: "z", bar: []int{8, 9}}},
want: true,
},
{
name: "not unique ",
d: []data{{foo: "m"}, {foo: "x", bar: []int{1}}, {foo: "x", bar: []int{8, 9}}},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := gofp.IsUniqueWithKeyBuilder(tt.d, func(t data) string { return t.foo })
assert.Equalf(t, tt.want, got, "Got %+v, want %+v", tt.want, got)
})
}
}

func BenchmarkIsUnique_Int(b *testing.B) {
slice1 := []int{1, 2, 3, 4, 5}

Expand Down Expand Up @@ -92,3 +122,36 @@ func BenchmarkIsUnique_Int_Pessimistic(b *testing.B) {
gofp.IsUnique(slice1)
}
}

func BenchmarkIsUniqueWithKeyBuilder_Int(b *testing.B) {
slice1 := []int{1, 2, 3, 4, 5}

b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
gofp.IsUnique(slice1)
}
}

func BenchmarkIsUniqueWithKeyBuilder_Int_Optimistic(b *testing.B) {
slice1 := []int{1, 1, 2, 3, 4, 5}

b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
gofp.IsUnique(slice1)
}
}

func BenchmarkIsUniqueWithKeyBuilder_Int_Pessimistic(b *testing.B) {
slice1 := []int{1, 2, 3, 4, 5, 1}

b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
gofp.IsUnique(slice1)
}
}

0 comments on commit 3019266

Please sign in to comment.