github.com/richardwilkes/toolbox@v1.121.0/collection/set.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package collection 11 12 // Set holds a set of values. 13 type Set[T comparable] map[T]struct{} 14 15 // NewSet creates a new set from its input values. 16 func NewSet[T comparable](values ...T) Set[T] { 17 s := make(Set[T], len(values)) 18 s.Add(values...) 19 return s 20 } 21 22 // Len returns the number of values in the set. 23 func (s Set[T]) Len() int { 24 return len(s) 25 } 26 27 // Empty returns true if there are no values in the set. 28 func (s Set[T]) Empty() bool { 29 return len(s) == 0 30 } 31 32 // Clear the set. 33 func (s *Set[T]) Clear() { 34 *s = make(Set[T]) 35 } 36 37 // Add values to the set. 38 func (s Set[T]) Add(values ...T) { 39 for _, v := range values { 40 s[v] = struct{}{} 41 } 42 } 43 44 // Contains returns true if the value exists within the set. 45 func (s Set[T]) Contains(value T) bool { 46 _, ok := s[value] 47 return ok 48 } 49 50 // Clone returns a copy of the set. 51 func (s Set[T]) Clone() Set[T] { 52 if s == nil { 53 return nil 54 } 55 clone := make(Set[T], len(s)) 56 for value := range s { 57 clone[value] = struct{}{} 58 } 59 return clone 60 } 61 62 // Values returns all values in the set. 63 func (s Set[T]) Values() []T { 64 values := make([]T, 0, len(s)) 65 for v := range s { 66 values = append(values, v) 67 } 68 return values 69 }