diff options
Diffstat (limited to 'utils/collections/set.go')
| -rw-r--r-- | utils/collections/set.go | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/utils/collections/set.go b/utils/collections/set.go new file mode 100644 index 0000000..79e1ae2 --- /dev/null +++ b/utils/collections/set.go @@ -0,0 +1,38 @@ +package collections + +type Set[T comparable] struct { + items []T + index map[T]bool +} + +func SetOf[T comparable](items ...T) Set[T] { + index := make(map[T]bool, len(items)) + uniqueItems := make([]T, 0, len(items)) + + for _, item := range items { + if index[item] { + continue + } + index[item] = true + uniqueItems = append(uniqueItems, item) + } + + return Set[T]{ + items: uniqueItems, + index: index, + } +} + +func (set Set[T]) Contains(item T) bool { + return set.index[item] +} + +func (set Set[T]) All() []T { + copied := make([]T, len(set.items)) + copy(copied, set.items) + return copied +} + +func (set Set[T]) Len() int { + return len(set.items) +} |
