1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-19 04:02:27 +08:00

feat: add Keys and Values function for hashmap

This commit is contained in:
dudaodong
2022-10-10 16:34:05 +08:00
parent fab24c8d12
commit bcd1cabf80
2 changed files with 48 additions and 13 deletions

View File

@@ -93,27 +93,45 @@ func (hm *HashMap) Contains(key any) bool {
return node != nil return node != nil
} }
// Iterate executes iteratee funcation for every key and value pair of hashmap // Iterate executes iteratee funcation for every key and value pair of hashmap (random order)
func (hm *HashMap) Iterate(iteratee func(key, value any)) { func (hm *HashMap) Iterate(iteratee func(key, value any)) {
if hm.size > 0 { if hm.size > 0 {
for _, item := range hm.table { for i := 0; i < len(hm.table); i++ {
iteratee(item.key, item.value) item := hm.table[i]
if item != nil {
iteratee(item.key, item.value)
}
} }
} }
} }
// Keys returns a slice of the hashmap's keys // Keys returns a slice of the hashmap's keys (random order)
// func (hm *HashMap) Keys() []any { func (hm *HashMap) Keys() []any {
// keys := make([]any, int(hm.size)) keys := make([]any, int(hm.size))
index := 0
if hm.size > 0 {
hm.Iterate(func(key, value any) {
keys[index] = key
index++
})
}
// var i int return keys
// for k := range m { }
// keys[i] = k
// i++
// }
// return keys // Values returns a slice of the hashmap's keys (random order)
// } func (hm *HashMap) Values() []any {
values := make([]any, int(hm.size))
index := 0
if hm.size > 0 {
hm.Iterate(func(key, value any) {
values[index] = value
index++
})
}
return values
}
func (hm *HashMap) resize() { func (hm *HashMap) resize() {
hm.capacity <<= 1 hm.capacity <<= 1

View File

@@ -52,3 +52,20 @@ func TestHashMap_Contains(t *testing.T) {
hm.Put("abc", 3) hm.Put("abc", 3)
assert.Equal(true, hm.Contains("abc")) assert.Equal(true, hm.Contains("abc"))
} }
func TestHashMap_KeysValues(t *testing.T) {
assert := internal.NewAssert(t, "TestHashMap_KeysValues")
hm := NewHashMap()
hm.Put("a", 1)
hm.Put("b", 2)
hm.Put("c", 3)
keys := hm.Keys()
values := hm.Values()
t.Log(keys, values)
assert.Equal(3, len(values))
assert.Equal(3, len(keys))
}