set.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package utils
  14. type Set[T comparable] map[T]struct{}
  15. func NewSet[T comparable](v ...T) Set[T] {
  16. if len(v) == 0 {
  17. return make(Set[T])
  18. }
  19. out := make(Set[T], len(v))
  20. for i := range v {
  21. out.Add(v[i])
  22. }
  23. return out
  24. }
  25. func (s Set[T]) Has(v T) bool {
  26. _, ok := s[v]
  27. return ok
  28. }
  29. func (s Set[T]) Add(v T) {
  30. s[v] = struct{}{}
  31. }
  32. func (s Set[T]) AddAll(v ...T) {
  33. for _, e := range v {
  34. s[e] = struct{}{}
  35. }
  36. }
  37. func (s Set[T]) Remove(v T) bool {
  38. _, ok := s[v]
  39. if ok {
  40. delete(s, v)
  41. }
  42. return ok
  43. }
  44. func (s Set[T]) Clear() {
  45. for v := range s {
  46. delete(s, v)
  47. }
  48. }
  49. func (s Set[T]) Elements() []T {
  50. elements := make([]T, 0, len(s))
  51. for v := range s {
  52. elements = append(elements, v)
  53. }
  54. return elements
  55. }
  56. func (s Set[T]) RemoveAll(elements ...T) {
  57. for _, e := range elements {
  58. s.Remove(e)
  59. }
  60. }
  61. func (s Set[T]) Diff(other Set[T]) Set[T] {
  62. out := make(Set[T])
  63. for k := range s {
  64. if _, ok := other[k]; !ok {
  65. out[k] = struct{}{}
  66. }
  67. }
  68. return out
  69. }
  70. func (s Set[T]) Union(other Set[T]) Set[T] {
  71. out := make(Set[T])
  72. for k := range s {
  73. out[k] = struct{}{}
  74. }
  75. for k := range other {
  76. out[k] = struct{}{}
  77. }
  78. return out
  79. }