mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 08:32:40 +08:00
array
This commit is contained in:
35
collections/generics/array.go
Normal file
35
collections/generics/array.go
Normal 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
|
||||
}
|
12
collections/generics/array_test.go
Normal file
12
collections/generics/array_test.go
Normal 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())
|
||||
}
|
@ -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
|
||||
|
@ -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))
|
||||
}
|
||||
|
Reference in New Issue
Block a user