mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
fix: use loop to get value . On Get() and Contains() (#124)
* fix: use loop to get value . On Get() and Contains() * fix: Use reflect. DeepEqual() determines whether the keys are equal
This commit is contained in:
@@ -7,6 +7,7 @@ package datastructure
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash/fnv"
|
"hash/fnv"
|
||||||
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultMapCapacity uint64 = 1 << 10
|
var defaultMapCapacity uint64 = 1 << 10
|
||||||
@@ -45,13 +46,24 @@ func NewHashMapWithCapacity(size, capacity uint64) *HashMap {
|
|||||||
func (hm *HashMap) Get(key any) any {
|
func (hm *HashMap) Get(key any) any {
|
||||||
hashValue := hm.hash(key)
|
hashValue := hm.hash(key)
|
||||||
node := hm.table[hashValue]
|
node := hm.table[hashValue]
|
||||||
if node != nil {
|
for node != nil {
|
||||||
return node.value
|
if reflect.DeepEqual(node.key, key) {
|
||||||
|
return node.value
|
||||||
|
}
|
||||||
|
node = node.next
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrDefault return the value of given key in hashmap, if not found return default value
|
||||||
|
func (hm *HashMap) GetOrDefault(key any, defaultValue any) any {
|
||||||
|
value := hm.Get(key)
|
||||||
|
if value == nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
// Put new key value in hashmap
|
// Put new key value in hashmap
|
||||||
func (hm *HashMap) Put(key any, value any) {
|
func (hm *HashMap) Put(key any, value any) {
|
||||||
hm.putValue(hm.hash(key), key, value)
|
hm.putValue(hm.hash(key), key, value)
|
||||||
@@ -90,7 +102,13 @@ func (hm *HashMap) Delete(key any) {
|
|||||||
// Contains checks if given key is in hashmap or not
|
// Contains checks if given key is in hashmap or not
|
||||||
func (hm *HashMap) Contains(key any) bool {
|
func (hm *HashMap) Contains(key any) bool {
|
||||||
node := hm.table[hm.hash(key)]
|
node := hm.table[hm.hash(key)]
|
||||||
return node != nil
|
for node != nil {
|
||||||
|
if reflect.DeepEqual(node.key, key) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
node = node.next
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iterate executes iteratee funcation for every key and value pair of hashmap (random order)
|
// Iterate executes iteratee funcation for every key and value pair of hashmap (random order)
|
||||||
|
|||||||
Reference in New Issue
Block a user