| |
| |
| |
|
|
| |
| |
|
|
| |
| package orderedmap |
|
|
| |
| type Map[K, V any] struct { |
| root *node[K, V] |
| compare func(K, K) int |
| } |
|
|
| |
| type node[K, V any] struct { |
| key K |
| val V |
| left, right *node[K, V] |
| } |
|
|
| |
| func New[K, V any](compare func(K, K) int) *Map[K, V] { |
| return &Map[K, V]{compare: compare} |
| } |
|
|
| |
| |
| |
| func (m *Map[K, V]) find(key K) **node[K, V] { |
| pn := &m.root |
| for *pn != nil { |
| switch cmp := m.compare(key, (*pn).key); { |
| case cmp < 0: |
| pn = &(*pn).left |
| case cmp > 0: |
| pn = &(*pn).right |
| default: |
| return pn |
| } |
| } |
| return pn |
| } |
|
|
| |
| |
| |
| func (m *Map[K, V]) Insert(key K, val V) bool { |
| pn := m.find(key) |
| if *pn != nil { |
| (*pn).val = val |
| return false |
| } |
| *pn = &node[K, V]{key: key, val: val} |
| return true |
| } |
|
|
| |
| |
| func (m *Map[K, V]) Find(key K) (V, bool) { |
| pn := m.find(key) |
| if *pn == nil { |
| var zero V |
| return zero, false |
| } |
| return (*pn).val, true |
| } |
|
|
| |
| type keyValue[K, V any] struct { |
| key K |
| val V |
| } |
|
|
| |
| func (m *Map[K, V]) InOrder() *Iterator[K, V] { |
| sender, receiver := chans_Ranger[keyValue[K, V]]() |
| var f func(*node[K, V]) bool |
| f = func(n *node[K, V]) bool { |
| if n == nil { |
| return true |
| } |
| |
| |
| return f(n.left) && |
| sender.Send(keyValue[K, V]{n.key, n.val}) && |
| f(n.right) |
| } |
| go func() { |
| f(m.root) |
| sender.Close() |
| }() |
| return &Iterator[K, V]{receiver} |
| } |
|
|
| |
| type Iterator[K, V any] struct { |
| r *chans_Receiver[keyValue[K, V]] |
| } |
|
|
| |
| |
| func (it *Iterator[K, V]) Next() (K, V, bool) { |
| keyval, ok := it.r.Next() |
| if !ok { |
| var zerok K |
| var zerov V |
| return zerok, zerov, false |
| } |
| return keyval.key, keyval.val, true |
| } |
|
|
| |
|
|
| func chans_Ranger[T any]() (*chans_Sender[T], *chans_Receiver[T]) |
|
|
| |
| type chans_Sender[T any] struct { |
| values chan<- T |
| done <-chan bool |
| } |
|
|
| func (s *chans_Sender[T]) Send(v T) bool { |
| select { |
| case s.values <- v: |
| return true |
| case <-s.done: |
| return false |
| } |
| } |
|
|
| func (s *chans_Sender[T]) Close() { |
| close(s.values) |
| } |
|
|
| type chans_Receiver[T any] struct { |
| values <-chan T |
| done chan<- bool |
| } |
|
|
| func (r *chans_Receiver[T]) Next() (T, bool) { |
| v, ok := <-r.values |
| return v, ok |
| } |
|
|