From 6386ab908d507da505ef06585016951ef70768da Mon Sep 17 00:00:00 2001 From: Faucherwind <82499314+Sigfied@users.noreply.github.com> Date: Tue, 1 Aug 2023 11:14:45 +0800 Subject: [PATCH] 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 --- datastructure/hashmap/hashmap.go | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/datastructure/hashmap/hashmap.go b/datastructure/hashmap/hashmap.go index d46e298..d754476 100644 --- a/datastructure/hashmap/hashmap.go +++ b/datastructure/hashmap/hashmap.go @@ -7,6 +7,7 @@ package datastructure import ( "fmt" "hash/fnv" + "reflect" ) var defaultMapCapacity uint64 = 1 << 10 @@ -45,13 +46,24 @@ func NewHashMapWithCapacity(size, capacity uint64) *HashMap { func (hm *HashMap) Get(key any) any { hashValue := hm.hash(key) node := hm.table[hashValue] - if node != nil { - return node.value + for node != nil { + if reflect.DeepEqual(node.key, key) { + return node.value + } + node = node.next } - 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 func (hm *HashMap) Put(key any, value any) { 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 func (hm *HashMap) Contains(key any) bool { 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)