github.com/searKing/golang/go@v1.2.117/container/hashmap/hashmap.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package hashmap 6 7 import ( 8 "errors" 9 ) 10 11 // HashMap is an auto make map 12 type HashMap struct { 13 m map[any]any 14 } 15 type Pair struct { 16 Key any 17 Value any 18 } 19 20 func New() *HashMap { 21 return &HashMap{} 22 } 23 24 // Init initializes or clears map m. 25 func (m *HashMap) Init() *HashMap { 26 m.m = make(map[any]any) 27 return m 28 } 29 30 // lazyInit lazily initializes a zero map value. 31 func (m *HashMap) lazyInit() { 32 if m.m == nil { 33 m.Init() 34 } 35 } 36 37 func (m *HashMap) Keys() []any { 38 var keys []any 39 for key, _ := range m.m { 40 keys = append(keys, key) 41 } 42 return keys 43 } 44 func (m *HashMap) Values() []any { 45 var values []any 46 for _, value := range m.m { 47 values = append(values, value) 48 } 49 return values 50 } 51 52 func (m *HashMap) Pairs() []Pair { 53 var pairs []Pair 54 for key, value := range m.m { 55 pairs = append(pairs, Pair{ 56 Key: key, 57 Value: value, 58 }) 59 } 60 return pairs 61 } 62 func (m *HashMap) AddPair(pair Pair) error { 63 return m.Add(pair.Key, pair.Value) 64 } 65 66 // add adds Key to the head of the linked list. 67 func (m *HashMap) Add(key, value any) error { 68 m.lazyInit() 69 if _, ok := m.m[key]; ok { 70 return errors.New("Key was already in HashMap") 71 } 72 m.m[key] = value 73 return nil 74 } 75 76 func (m *HashMap) AddOrUpdate(key any, value any) { 77 m.Remove(key) 78 m.Add(key, value) 79 } 80 81 // Remove removes Key from cl. 82 func (m *HashMap) Remove(key any) any { 83 if v, ok := m.m[key]; ok { 84 delete(m.m, key) 85 return v 86 } 87 return nil 88 } 89 90 func (m *HashMap) Clear() { 91 m.m = nil 92 } 93 func (m *HashMap) Find(key any) (any, bool) { 94 v, ok := m.m[key] 95 return v, ok 96 } 97 98 func (m *HashMap) Contains(key any) bool { 99 _, ok := m.m[key] 100 return ok 101 } 102 103 func (m *HashMap) Peek(key any) (any, bool) { 104 v, ok := m.m[key] 105 if ok { 106 m.Remove(key) 107 } 108 return v, ok 109 } 110 111 // Len returns the number of items in the cache. 112 func (m *HashMap) Len() int { 113 return len(m.m) 114 } 115 116 func (m *HashMap) Count() int { 117 return m.Len() 118 } 119 func (m *HashMap) Size() int { 120 return m.Len() 121 }