Skip to content

Commit

Permalink
Merge pull request #1289 from donutloop/interal-opt-uniq
Browse files Browse the repository at this point in the history
internal: optimized uniq function
  • Loading branch information
ploxiln committed Oct 29, 2020
2 parents e989f96 + 8358033 commit f7c6ac3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
9 changes: 3 additions & 6 deletions internal/stringy/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,14 @@ func Union(s []string, a []string) []string {
}

func Uniq(s []string) (r []string) {
outerLoop:
for _, entry := range s {
found := false
for _, existing := range r {
if existing == entry {
found = true
break
continue outerLoop
}
}
if !found {
r = append(r, entry)
}
r = append(r, entry)
}
return
}
24 changes: 24 additions & 0 deletions internal/stringy/slice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package stringy_test

import (
"github.com/nsqio/nsq/internal/stringy"
"testing"
)

func BenchmarkUniq(b *testing.B) {
values := []string{"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b"}
for i := 0; i < b.N; i++ {
values = stringy.Uniq(values)
if len(values) != 2 {
b.Fatal("values len is incorrect")
}
}
}

func TestUniq(t *testing.T) {
values := []string{"a", "a", "a", "b", "b", "b", "c", "c", "c"}
values = stringy.Uniq(values)
if len(values) != 3 {
t.Fatal("values len is incorrect")
}
}

0 comments on commit f7c6ac3

Please sign in to comment.