1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00
This commit is contained in:
2022-04-07 15:26:49 +08:00
parent cfa90dff4f
commit 9ff187c944
4 changed files with 58 additions and 0 deletions

View File

@ -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
}

View File

@ -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())
}

View File

@ -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

View File

@ -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))
}