A simple naive hashmap implementation.

master
Zed A. Shaw 4 days ago
parent d29998a797
commit 430536da5a
  1. 52
      hashmap/impl.go
  2. 27
      tests/hashmap_test.go

@ -0,0 +1,52 @@
package hashmap
import (
"hash/crc32"
)
const (
BucketCount = 256
)
type HashNode struct {
key string
val any
}
type HashBucket struct {
contents []HashNode
}
type Hashmap struct {
buckets [BucketCount]HashBucket
}
func New() *Hashmap {
hmap := new(Hashmap)
return hmap
}
func (hmap *Hashmap) Hash(key string) uint32 {
return crc32.ChecksumIEEE([]byte(key)) % BucketCount
}
func (hmap *Hashmap) Add(key string, val any) {
id := hmap.Hash(key)
the_bucket := &hmap.buckets[id]
node := HashNode{key, val}
the_bucket.contents = append(the_bucket.contents, node)
}
func (hmap *Hashmap) Get(key string) any {
id := hmap.Hash(key)
the_bucket := &hmap.buckets[id]
for _, node := range the_bucket.contents {
if node.key == key {
return node.val
}
}
return nil
}

@ -0,0 +1,27 @@
package tests
import (
"testing"
"github.com/stretchr/testify/assert"
"MY/dsa/hashmap"
)
func TestHashmap(t *testing.T) {
hmap := hashmap.New()
hmap.Add("zed", 100)
hmap.Add("joe", "That Thing")
hmap.Add("mary", 300.10)
val := hmap.Get("zed")
assert.Equal(t, val, 100, "bad zed")
val2 := hmap.Get("joe")
assert.Equal(t, val2, "That Thing", "bad joe")
val3 := hmap.Get("mary")
assert.Equal(t, val3, 300.10, "bad mary")
val4 := hmap.Get("nothere")
assert.Equal(t, val4, nil, "bad missing")
}
Loading…
Cancel
Save