set.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package arrays
  2. import (
  3. // "sort"
  4. "sync"
  5. "reflect"
  6. )
  7. type Set struct {
  8. m map[interface{}]bool
  9. sync.RWMutex
  10. }
  11. func MakeSet(i ...interface{}) *Set {
  12. s := &Set{
  13. m: map[interface{}]bool{},
  14. }
  15. for _, d := range i {
  16. s.m[d] = true
  17. }
  18. return s
  19. }
  20. func (s *Set) Add(item interface{}) {
  21. s.Lock()
  22. defer s.Unlock()
  23. s.m[item] = true
  24. }
  25. // func (s *Set) Remove(item int) {
  26. // s.Lock()
  27. // defer s.Unlock()
  28. // delete(s.m, item)
  29. // }
  30. func (s *Set) Has(item interface{}) bool {
  31. s.RLock()
  32. defer s.RUnlock()
  33. _, ok := s.m[item]
  34. return ok
  35. }
  36. func (s *Set) Len() int {
  37. return len(s.List())
  38. }
  39. func (s *Set) Clear() {
  40. s.Lock()
  41. defer s.Unlock()
  42. s.m = map[interface{}]bool{}
  43. }
  44. func (s *Set) IsEmpty() bool {
  45. if s.Len() == 0 {
  46. return true
  47. }
  48. return false
  49. }
  50. func (s *Set) List() []interface{} {
  51. s.RLock()
  52. defer s.RUnlock()
  53. list := make([]interface{}, 0)
  54. for item := range s.m {
  55. list = append(list, item)
  56. }
  57. return list
  58. }
  59. func (s *Set) Strings() []string {
  60. s.RLock()
  61. defer s.RUnlock()
  62. list := make([]string, 0)
  63. for item := range s.m {
  64. list = append(list, reflect.ValueOf(item).String())
  65. }
  66. return list
  67. }
  68. func (s *Set) Ints() []int64 {
  69. s.RLock()
  70. defer s.RUnlock()
  71. list := make([]int64, 0)
  72. for item := range s.m {
  73. list = append(list, reflect.ValueOf(item).Int())
  74. }
  75. return list
  76. }
  77. func (s *Set) Floats() []float64 {
  78. s.RLock()
  79. defer s.RUnlock()
  80. list := make([]float64, 0)
  81. for item := range s.m {
  82. list = append(list, reflect.ValueOf(item).Float())
  83. }
  84. return list
  85. }
  86. // func (s *Set) SortList() []interface{} {
  87. // s.RLock()
  88. // defer s.RUnlock()
  89. // list := make([]interface{}, 0)
  90. // for item := range s.m {
  91. // list = append(list, item)
  92. // }
  93. // sort.Ints(list)
  94. // return list
  95. // }