2024-06-23 06:45:58 -06:00
|
|
|
package ucontainer
|
|
|
|
|
|
|
|
// Set is a set of unique items, built on top of map.
|
|
|
|
type Set[T comparable] map[T] struct { }
|
|
|
|
|
2024-09-20 15:07:16 -06:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2024-06-23 06:45:58 -06:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|