src

Go monorepo.
Log | Files | Refs

commit 1523337fe467711f82fb521e326f2b122eb30d3b
parent 41562c5cfe2cb6802b2286e35d0d1f15513e4129
Author: dwrz <dwrz@dwrz.net>
Date:   Tue, 10 Jan 2023 01:18:02 +0000

Add unique pkg

Diffstat:
Apkg/unique/unique.go | 14++++++++++++++
Apkg/unique/unique_test.go | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 115 insertions(+), 0 deletions(-)

diff --git a/pkg/unique/unique.go b/pkg/unique/unique.go @@ -0,0 +1,14 @@ +package unique + +func Unique[T comparable](s []T) (r []T) { + var unique = map[T]struct{}{} + + for _, v := range s { + if _, exists := unique[v]; !exists { + unique[v] = struct{}{} + r = append(r, v) + } + } + + return r +} diff --git a/pkg/unique/unique_test.go b/pkg/unique/unique_test.go @@ -0,0 +1,101 @@ +package unique + +import "testing" + +func TestString(t *testing.T) { + var tests = []struct { + Input []string + Expected []string + }{ + { + Input: nil, + Expected: nil, + }, + { + Input: []string{}, + Expected: []string{}, + }, + { + Input: []string{"a", "b", "c", "d"}, + Expected: []string{"a", "b", "c", "d"}, + }, + { + Input: []string{ + "a", "b", "c", "d", "a", "b", "c", "d", + }, + Expected: []string{"a", "b", "c", "d"}, + }, + } + + for _, test := range tests { + res := Unique(test.Input) + + if len(res) != len(test.Expected) { + t.Errorf( + "expected %d values, but got %d", + len(test.Expected), len(res), + ) + return + } + for i := range test.Expected { + if res[i] != test.Expected[i] { + t.Errorf( + "expected value %v but got %v", + res[i], test.Expected[i], + ) + return + } + } + + t.Logf("%v %v", res, test.Expected) + } + +} + +func TestInt(t *testing.T) { + var tests = []struct { + Input []int + Expected []int + }{ + { + Input: nil, + Expected: nil, + }, + { + Input: []int{}, + Expected: []int{}, + }, + { + Input: []int{1, 2, 3, 4}, + Expected: []int{1, 2, 3, 4}, + }, + { + Input: []int{1, 2, 3, 4, 1, 2, 3, 4}, + Expected: []int{1, 2, 3, 4}, + }, + } + + for _, test := range tests { + res := Unique(test.Input) + + if len(res) != len(test.Expected) { + t.Errorf( + "expected %d values, but got %d", + len(test.Expected), len(res), + ) + return + } + for i := range test.Expected { + if res[i] != test.Expected[i] { + t.Errorf( + "expected value %v but got %v", + res[i], test.Expected[i], + ) + return + } + } + + t.Logf("%v %v", res, test.Expected) + } + +}