diff --git a/data-structures/hash-tables/ht.go b/data-structures/hash-tables/ht.go index 45141cc..e94282e 100644 --- a/data-structures/hash-tables/ht.go +++ b/data-structures/hash-tables/ht.go @@ -5,7 +5,7 @@ package ht import ( "errors" - "github.com/arnauddri/algorithms/data-structures/linked-list" + list "github.com/arnauddri/algorithms/data-structures/linked-list" "math" ) @@ -115,3 +115,17 @@ func hashCode(s string) int { } return int(math.Abs(float64(hash))) } + +// Resizes table to desired capacity. ( if Possible ) +func (ht *HashTable) Resize(newCap int) error { + size := ht.Size + if ht.Capacity == newCap { + return errors.New("current capacity is as same the input number") + } + if newCap >= size { + ht.Capacity = newCap + } else { + return errors.New("there is not enough capacity to hold items. please enter a larger number") + } + return nil +} diff --git a/data-structures/hash-tables/ht_test.go b/data-structures/hash-tables/ht_test.go index c4c59ec..6e121a2 100644 --- a/data-structures/hash-tables/ht_test.go +++ b/data-structures/hash-tables/ht_test.go @@ -55,3 +55,32 @@ func TestHash(t *testing.T) { t.Error() } } + +func TestHashTable_Resize(t *testing.T) { + ht := New(1000) + ht.Put("foo", "bar") + ht.Put("fiz", "buzz") + ht.Put("bruce", "wayne") + ht.Put("peter", "parker") + ht.Put("clark", "kent") + + actual := ht.Resize(10) + + if actual != nil { + t.Errorf("resul = %v, want nil", actual) + } + + actual = ht.Resize(10) + expected := "current capacity is as same the input number" + + if actual.Error() != expected { + t.Errorf("resul = %v, want %v", actual, expected) + } + + actual = ht.Resize(4) + expected = "there is not enough capacity to hold items. please enter a larger number" + + if actual.Error() != expected { + t.Errorf("resul = %v, want %v", actual, expected) + } +}