Skip to content

Commit

Permalink
[TASK] TRK-3040 Network - Conversion Ratio rules - microservice part (#…
Browse files Browse the repository at this point in the history
…32)

* [TASK] TRK-3040 Add function to test uniqueness of any comparable slice.

* Remove comparable from indexed set value
  • Loading branch information
Skandalik authored Apr 12, 2024
1 parent 7650791 commit d1d0b87
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 1 deletion.
2 changes: 1 addition & 1 deletion gofp/indexed_set.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package gofp

// IndexedSet works like a map but it keeps the order.
type IndexedSet[Key, Value comparable] struct {
type IndexedSet[Key comparable, Value any] struct {
m map[Key]Value
i []Key
}
Expand Down
16 changes: 16 additions & 0 deletions gofp/unique.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package gofp

// IsUnique checks if all elements in a slice are unique.
func IsUnique[T comparable](el []T) bool {
seen := map[T]bool{}
for _, t := range el {
_, ok := seen[t]
if ok {
return false
}

seen[t] = true
}

return true
}
94 changes: 94 additions & 0 deletions gofp/unique_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package gofp_test

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/msales/gox/gofp"
)

func TestIsUnique_Int(t *testing.T) {
type test struct {
name string
data []int
want bool
}
tests := []test{
{
name: "unique",
data: []int{1, 2, 3, 4, 5},
want: true,
},
{
name: "not unique",
data: []int{1, 2, 3, 4, 5, 1},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := gofp.IsUnique(tt.data)
assert.Equalf(t, tt.want, got, "Got %+v, want %+v", tt.want, got)
})
}
}

func TestIsUnique_String(t *testing.T) {
type test struct {
name string
data []string
want bool
}
tests := []test{
{
name: "unique",
data: []string{"foo", "bar", "baz"},
want: true,
},
{
name: "not unique",
data: []string{"foo", "bar", "baz", "foo"},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := gofp.IsUnique(tt.data)
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}

b.ReportAllocs()
b.ResetTimer()

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

func BenchmarkIsUnique_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 BenchmarkIsUnique_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 d1d0b87

Please sign in to comment.