Skip to content

Commit

Permalink
refactor remove duplicates, move to utils, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
notque committed Oct 27, 2023
1 parent 25b1110 commit 5a9b393
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 13 deletions.
13 changes: 0 additions & 13 deletions internal/storage/elasticsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,19 +327,6 @@ func (es ElasticSearch) GetAttributes(filter *AttributeFilter, tenantID string)
return unique, nil
}

// RemoveDuplicates removes duplicates from a slice of strings while preserving the order.
func RemoveDuplicates(s []string) []string {
seen := make(map[string]struct{}, len(s))
var result []string
for _, v := range s {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
result = append(result, v)
}
}
return result
}

// MaxLimit grabs the configured maxlimit for results
func (es ElasticSearch) MaxLimit() uint {
return uint(viper.GetInt("elasticsearch.max_result_window"))
Expand Down
15 changes: 15 additions & 0 deletions internal/storage/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package storage

// RemoveDuplicates removes duplicates from a slice of strings while preserving the order.
func RemoveDuplicates(s []string) []string {
seen := make(map[string]struct{}, len(s))
var result []string
for _, v := range s {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
result = append(result, v)
}
}

return result
}
44 changes: 44 additions & 0 deletions internal/storage/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package storage

import (
"reflect"
"testing"
)

func TestRemoveDuplicates(t *testing.T) {
tests := []struct {
name string
input []string
expected []string
}{
{
name: "No duplicates",
input: []string{"apple", "banana", "cherry"},
expected: []string{"apple", "banana", "cherry"},
},
{
name: "With duplicates",
input: []string{"apple", "banana", "cherry", "apple", "cherry"},
expected: []string{"apple", "banana", "cherry"},
},
{
name: "All duplicates",
input: []string{"apple", "apple", "apple"},
expected: []string{"apple"},
},
{
name: "Single element",
input: []string{"apple"},
expected: []string{"apple"},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
output := RemoveDuplicates(tt.input)
if !reflect.DeepEqual(output, tt.expected) {
t.Errorf("got %v, want %v", output, tt.expected)
}
})
}
}

0 comments on commit 5a9b393

Please sign in to comment.