Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hash table Resize #18

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion data-structures/hash-tables/ht.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
29 changes: 29 additions & 0 deletions data-structures/hash-tables/ht_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}