43 lines
869 B
Go
43 lines
869 B
Go
package ucontainer
|
|
|
|
// Set is a set of unique items, built on top of map.
|
|
type Set[T comparable] map[T] struct { }
|
|
|
|
// NewSet creates a new set that contains all specified items.
|
|
func NewSet[T comparable] (items ...T) Set[T] {
|
|
set := make(Set[T])
|
|
for _, item := range items {
|
|
set.Add(item)
|
|
}
|
|
return set
|
|
}
|
|
|
|
// Empty returns true if there are no items in the set.
|
|
func (set Set[T]) Empty () bool {
|
|
return set == nil || len(set) == 0
|
|
}
|
|
|
|
// Has returns true if the set contains item.
|
|
func (set Set[T]) Has (item T) bool {
|
|
if set == nil {
|
|
return false
|
|
}
|
|
_, ok := set[item]
|
|
return ok
|
|
}
|
|
|
|
// Add adds an item to the set.
|
|
func (set Set[T]) Add (item T) {
|
|
set[item] = struct { } { }
|
|
}
|
|
|
|
// Pop removes the first accessible item from the set and returns it.
|
|
func (set Set[T]) Pop () (item T) {
|
|
for item := range set {
|
|
delete(set, item)
|
|
return item
|
|
}
|
|
return
|
|
}
|
|
|