ordered.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package maps
  2. // The type makes the underlying map ordered,
  3. // so every time you pass through all the values
  4. // they will be in the same order.
  5. type orderedMap[K comparable, V any] struct {
  6. store map[K] V
  7. keys []K
  8. }
  9. // Returns the new empty ordered map.
  10. func NewOrdered[K comparable, V any]() Map[K, V] {
  11. return &orderedMap[K, V]{
  12. store: make(map[K] V),
  13. }
  14. }
  15. func (m *orderedMap[K, V]) Clear() {
  16. m.store = map[K]V{}
  17. m.keys = []K{}
  18. }
  19. func (m *orderedMap[K, V]) Set(k K, v V) {
  20. _, ok := m.store[k]
  21. if !ok {
  22. m.keys = append(m.keys, k)
  23. }
  24. m.store[k] = v
  25. }
  26. func (m *orderedMap[K, V]) Got(key K) (V, bool) {
  27. v, ok := m.store[key]
  28. return v, ok
  29. }
  30. func (m *orderedMap[K, V]) Has(k K) bool {
  31. _, ok := m.store[k]
  32. return ok
  33. }
  34. // Get the value from the map.
  35. func (m *orderedMap[K, V]) Get(k K) (V) {
  36. v := m.store[k]
  37. return v
  38. }
  39. func (m *orderedMap[K, V]) Del(k K) {
  40. delete(m.store, k)
  41. for i, v := range m.keys {
  42. if v == k {
  43. m.keys = append(m.keys[:i], m.keys[i+1:]...)
  44. }
  45. }
  46. }
  47. // Get map keys slice.
  48. func (m *orderedMap[K, V]) Keys() []K {
  49. return m.keys
  50. }
  51. func (m *orderedMap[K, V]) Values() []V {
  52. ret := make([]V, len(m.keys))
  53. i := 0
  54. for _, k := range m.keys {
  55. ret[i] = m.store[k]
  56. i++
  57. }
  58. return ret
  59. }
  60. func (m *orderedMap[K, V]) KeyChan() chan K {
  61. chn := make(chan K)
  62. go func() {
  63. for _, v := range m.keys {
  64. chn <- v
  65. }
  66. close(chn)
  67. }()
  68. return chn
  69. }
  70. // Return channel of ordered values.
  71. func (m *orderedMap[K, V]) Chan() chan V {
  72. chn := make(chan V)
  73. go func(){
  74. for _, k := range m.keys {
  75. chn <- m.Get(k)
  76. }
  77. close(chn)
  78. }()
  79. return chn
  80. }
  81. func (m *orderedMap[K, V]) Empty() bool {
  82. return len(m.keys) == 0
  83. }
  84. func (m *orderedMap[K, V]) Size() int {
  85. return len(m.keys)
  86. }