mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Delete method for hashmap
This commit is contained in:
@@ -78,6 +78,28 @@ func (hm *HashMap) putValue(hash uint64, key, value any) any {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delete key value in hashmap
|
||||||
|
// func (hm *HashMap) Delete(key any) {
|
||||||
|
// hm.deleteValue(hm.hash(key))
|
||||||
|
// }
|
||||||
|
|
||||||
|
func (hm *HashMap) Delete(key any) {
|
||||||
|
hash := hm.hash(key)
|
||||||
|
node := hm.table[hash]
|
||||||
|
if node == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hm.table = append(hm.table[:hash], hm.table[hash+1:]...)
|
||||||
|
hm.size--
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
func (hm *HashMap) resize() {
|
func (hm *HashMap) resize() {
|
||||||
hm.capacity <<= 1
|
hm.capacity <<= 1
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestHashMap_PutAndGet(t *testing.T) {
|
func TestHashMap_PutAndGet(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestHashMap_Get")
|
assert := internal.NewAssert(t, "TestHashMap_PutAndGet")
|
||||||
|
|
||||||
hm := NewHashMap()
|
hm := NewHashMap()
|
||||||
|
|
||||||
@@ -18,3 +18,25 @@ func TestHashMap_PutAndGet(t *testing.T) {
|
|||||||
hm.Put("abc", 4)
|
hm.Put("abc", 4)
|
||||||
assert.Equal(4, hm.Get("abc"))
|
assert.Equal(4, hm.Get("abc"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHashMap_Delete(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestHashMap_Delete")
|
||||||
|
|
||||||
|
hm := NewHashMap()
|
||||||
|
|
||||||
|
hm.Put("abc", 3)
|
||||||
|
assert.Equal(3, hm.Get("abc"))
|
||||||
|
|
||||||
|
hm.Delete("abc")
|
||||||
|
assert.IsNil(hm.Get("abc"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHashMap_Contains(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestHashMap_Contains")
|
||||||
|
|
||||||
|
hm := NewHashMap()
|
||||||
|
assert.Equal(false, hm.Contains("abc"))
|
||||||
|
|
||||||
|
hm.Put("abc", 3)
|
||||||
|
assert.Equal(true, hm.Contains("abc"))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user