From 9ff187c94455b262831da420aa0631939e5af6b4 Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Thu, 7 Apr 2022 15:26:49 +0800 Subject: [PATCH] array --- collections/generics/array.go | 35 ++++++++++++++++++++++++++++ collections/generics/array_test.go | 12 ++++++++++ collections/generics/hashset.go | 4 ++++ collections/generics/hashset_test.go | 7 ++++++ 4 files changed, 58 insertions(+) create mode 100644 collections/generics/array.go create mode 100644 collections/generics/array_test.go diff --git a/collections/generics/array.go b/collections/generics/array.go new file mode 100644 index 0000000..a8d61b7 --- /dev/null +++ b/collections/generics/array.go @@ -0,0 +1,35 @@ +package generics + +type Array[T comparable] struct { + data []T + length int +} + +func NewArray[T comparable](values ...T) *Array[T] { + return &Array[T]{data: values, length: len(values)} +} + +func (a *Array[T]) Distinct(keepSorted bool) *Array[T] { + set := NewHashSet(a.data...) + if set.Size() == a.length { + return a + } + + if !keepSorted { + return NewArray(set.Values()...) + } + + ret := make([]T, 0, len(set)) + for _, v := range a.data { + if set.Contain(v) { + ret = append(ret, v) + set.Remove(v) + } + } + + return NewArray(ret...) +} + +func (a *Array[T]) ToList() []T { + return a.data +} diff --git a/collections/generics/array_test.go b/collections/generics/array_test.go new file mode 100644 index 0000000..c74addb --- /dev/null +++ b/collections/generics/array_test.go @@ -0,0 +1,12 @@ +package generics + +import "testing" + +func TestArray(t *testing.T) { + a := NewArray(9, 1, 2, 4, 3, 1, 3) + t.Log(a) + + b := a.Distinct(true) + t.Log(b) + t.Log(b.ToList()) +} diff --git a/collections/generics/hashset.go b/collections/generics/hashset.go index 1758a49..6b47f55 100644 --- a/collections/generics/hashset.go +++ b/collections/generics/hashset.go @@ -15,6 +15,10 @@ func (s Set[T]) Add(values ...T) { } } +func (s Set[T]) Remove(v T) { + delete(s, v) +} + func (s Set[T]) Contain(value T) bool { _, ok := s[value] return ok diff --git a/collections/generics/hashset_test.go b/collections/generics/hashset_test.go index e13b8c2..774eb92 100644 --- a/collections/generics/hashset_test.go +++ b/collections/generics/hashset_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/charlienet/go-mixed/collections/generics" + "github.com/stretchr/testify/assert" ) func TestSet(t *testing.T) { @@ -15,3 +16,9 @@ func TestSet(t *testing.T) { _ = expected } + +func TestSetExist(t *testing.T) { + s := generics.NewHashSet(1, 2, 3) + assert.True(t, s.Contain(1)) + assert.False(t, s.Contain(5)) +}