github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zarray/sort.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package zarray
     5  
     6  type SortMaper[K hashable, V any] struct {
     7  	values *Maper[K, V]
     8  	keys   []K
     9  }
    10  
    11  func NewSortMap[K hashable, V any](size ...uintptr) *SortMaper[K, V] {
    12  	return &SortMaper[K, V]{
    13  		keys:   make([]K, 0),
    14  		values: NewHashMap[K, V](size...),
    15  	}
    16  }
    17  
    18  func (s *SortMaper[K, V]) Set(key K, value V) {
    19  	if !s.values.Has(key) {
    20  		s.keys = append(s.keys, key)
    21  	}
    22  	s.values.Set(key, value)
    23  }
    24  
    25  func (s *SortMaper[K, V]) Get(key K) (value V, ok bool) {
    26  	return s.values.Get(key)
    27  }
    28  
    29  func (s *SortMaper[K, V]) Has(key K) (ok bool) {
    30  	for _, v := range s.keys {
    31  		if v == key {
    32  			return true
    33  		}
    34  	}
    35  	return false
    36  }
    37  
    38  func (s *SortMaper[K, V]) Delete(key ...K) {
    39  	for i, v := range s.keys {
    40  		for _, k := range key {
    41  			if v == k {
    42  				s.keys = append(s.keys[:i], s.keys[i+1:]...)
    43  				break
    44  			}
    45  		}
    46  	}
    47  	s.values.Delete(key...)
    48  }
    49  
    50  func (s *SortMaper[K, V]) Len() int {
    51  	return len(s.keys)
    52  }
    53  
    54  func (s *SortMaper[K, V]) Keys() []K {
    55  	return s.keys
    56  }
    57  
    58  func (s *SortMaper[K, V]) ForEach(lambda func(K, V) bool) {
    59  	for i := range s.keys {
    60  		v, ok := s.values.Get(s.keys[i])
    61  		if ok && lambda(s.keys[i], v) {
    62  			continue
    63  		}
    64  		break
    65  	}
    66  }