uniq.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package maps
  2. // The type describing unique map
  3. // where you can quickly get both
  4. // value by key and vice versa.
  5. type Uniq[K, V comparable] interface {
  6. Map[K, V]
  7. GetByValue(V) K
  8. }
  9. type uniqMap[K, V comparable] struct {
  10. store map[K] V
  11. rstore map[V] K
  12. }
  13. // The function returns map type where
  14. // you can get, set and delete by value
  15. // since it store everything as ONLY entity
  16. // both for keys and values way.
  17. // Use only when you do not care about the order.
  18. func NewUniq[K, V comparable]() Uniq[K, V] {
  19. return &uniqMap[K, V]{
  20. map[K] V{},
  21. map[V] K{},
  22. }
  23. }
  24. func (m *uniqMap[K, V]) Empty() bool {
  25. return len(m.store) == 0
  26. }
  27. func (m *uniqMap[K, V]) Clear() {
  28. m.store = map[K] V{}
  29. m.rstore = map[V] K{}
  30. }
  31. func (m *uniqMap[K, V]) Has(k K) bool {
  32. _, ok := m.store[k]
  33. return ok
  34. }
  35. func (m *uniqMap[K, V]) Set(k K, v V) {
  36. m.store[k] = v
  37. m.rstore[v] = k
  38. }
  39. func (m *uniqMap[K, V]) Del(k K) {
  40. v := m.store[k]
  41. delete(m.store, k)
  42. delete(m.rstore, v)
  43. }
  44. func (m *uniqMap[K, V]) Get(k K) (V) {
  45. v := m.store[k]
  46. return v
  47. }
  48. func (m *uniqMap[K, V]) Got(k K) (V, bool) {
  49. v, ok := m.store[k]
  50. return v, ok
  51. }
  52. func (m *uniqMap[K, V]) Chan() chan V {
  53. ret := make(chan V)
  54. go func() {
  55. for _, v := range m.store {
  56. ret <- v
  57. }
  58. close(ret)
  59. }()
  60. return ret
  61. }
  62. func (m *uniqMap[K, V]) Keys() []K {
  63. ret := make([]K, len(m.store))
  64. i := 0
  65. for k := range m.store {
  66. ret[i] = k
  67. i++
  68. }
  69. return ret
  70. }
  71. func (m *uniqMap[K, V]) KeyChan() chan K {
  72. ret := make(chan K)
  73. go func() {
  74. for k := range m.store {
  75. ret <- k
  76. }
  77. close(ret)
  78. }()
  79. return ret
  80. }
  81. func (m *uniqMap[K, V]) Values() []V {
  82. ret := make([]V, len(m.store))
  83. i := 0
  84. for _, v := range m.store {
  85. ret[i] = v
  86. i++
  87. }
  88. return ret
  89. }
  90. func (m *uniqMap[K, V]) Size() int {
  91. return len(m.store)
  92. }
  93. func (m *uniqMap[K, V]) GetByValue(v V) (K) {
  94. k := m.rstore[v]
  95. return k
  96. }