set.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // CookieJar - A contestant's algorithm toolbox
  2. // Copyright (c) 2013 Peter Szilagyi. All rights reserved.
  3. //
  4. // CookieJar is dual licensed: use of this source code is governed by a BSD
  5. // license that can be found in the LICENSE file. Alternatively, the CookieJar
  6. // toolbox may be used in accordance with the terms and conditions contained
  7. // in a signed written agreement between you and the author(s).
  8. // Package set implements simple present/not data structure supporting arbitrary
  9. // types (even a mixture).
  10. //
  11. // Internally it uses a simple map assigning zero-byte struct{}s to keys.
  12. package set
  13. // Set data structure.
  14. type Set struct {
  15. data map[interface{}]struct{}
  16. }
  17. // Creates a new empty set.
  18. func New() *Set {
  19. return &Set{make(map[interface{}]struct{})}
  20. }
  21. // Inserts an element into the set.
  22. func (s *Set) Insert(val interface{}) {
  23. s.data[val] = struct{}{}
  24. }
  25. // Removes an element from the set. If none was present, nothing is done.
  26. func (s *Set) Remove(val interface{}) {
  27. delete(s.data, val)
  28. }
  29. // Returns the number of elements in the set.
  30. func (s *Set) Size() int {
  31. return len(s.data)
  32. }
  33. // Checks whether an element is inside the set.
  34. func (s *Set) Exists(val interface{}) bool {
  35. _, ok := s.data[val]
  36. return ok
  37. }
  38. // Executes a function for every element in the set.
  39. func (s *Set) Do(f func(interface{})) {
  40. for val, _ := range s.data {
  41. f(val)
  42. }
  43. }
  44. // Clears the contents of a set.
  45. func (s *Set) Reset() {
  46. *s = *New()
  47. }