Skip to content

Commit

Permalink
[xslices] added Unique function
Browse files Browse the repository at this point in the history
  • Loading branch information
kucherenkovova committed May 31, 2024
1 parent 386c5cf commit d6973fb
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 1 deletion.
3 changes: 2 additions & 1 deletion go.work
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
go 1.22.2
go 1.22.3

use (
./xmaps
./xmath
./xnet/xhttp
./xslices
./xslog
./xstrconv
)
7 changes: 7 additions & 0 deletions xslices/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# xslices
Extensions to the standard Go library's `slices` package.

### Install
```
go get github.com/kucherenkovova/gopypaste/[email protected]
```
3 changes: 3 additions & 0 deletions xslices/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/kucherenkovova/gopypaste/xslices

go 1.22.3
23 changes: 23 additions & 0 deletions xslices/slices.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package xslices

// Unique returns a new slice containing only the unique elements of the input slice.
// Only first occurrence of each element is preserved.
func Unique[T comparable](list []T) []T {
if list == nil {
return nil
}

seen := make(map[T]struct{}, len(list))
results := make([]T, 0, len(list))

for _, element := range list {
if _, ok := seen[element]; ok {
continue
}

seen[element] = struct{}{}
results = append(results, element)
}

return results
}
52 changes: 52 additions & 0 deletions xslices/slices_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package xslices_test

import (
"reflect"
"testing"

"github.com/kucherenkovova/gopypaste/xslices"
)

func TestUnique(t *testing.T) {
type testCase struct {
name string
in []string
want []string
}

tests := []testCase{
{
name: "empty list",
in: []string{},
want: []string{},
},
{
name: "nil",
in: nil,
want: nil,
},
{
name: "no duplicates",
in: []string{"a", "b", "c"},
want: []string{"a", "b", "c"},
},
{
name: "consequent duplicates",
in: []string{"a", "a", "b", "b", "c", "c"},
want: []string{"a", "b", "c"},
},
{
name: "non-consequent duplicates",
in: []string{"a", "b", "a", "c", "b", "c"},
want: []string{"a", "b", "c"},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := xslices.Unique(tt.in); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Unique() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit d6973fb

Please sign in to comment.