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
|
||||
}
|
Reference in New Issue
Block a user