Skip to content

Commit

Permalink
Dev
Browse files Browse the repository at this point in the history
  • Loading branch information
lindsaygelle committed Oct 17, 2023
1 parent e722ed1 commit e144b90
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
39 changes: 39 additions & 0 deletions hashtable.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,42 @@ func (hashtable *Hashtable[K, V]) KeysFunc(fn func(key K) bool) *slice.Slice[K]
})
return &keys
}

// Length returns the number of key-value pairs in the hashtable.
//
// Example:
//
// ht := make(hashtable.Hashtable[string, int])
// ht.Add("apple", 5)
// ht.Add("banana", 3)
// ht.Add("cherry", 8)
//
// length := ht.Length() // Result: 3
func (hashtable *Hashtable[K, V]) Length() int {
return len(*hashtable)
}

// Map applies a given function to all key-value pairs in the hashtable and returns a new hashtable with the transformed values.
// The original hashtable remains unchanged.
//
// Example:
//
// ht := make(hashtable.Hashtable[string, int])
// ht.Add("apple", 5)
// ht.Add("banana", 3)
// ht.Add("cherry", 8)
//
// // Define a function to double the values.
// doubleValue := func(key string, value int) int {
// return value * 2
// }
//
// // Apply the function to double the values in the hashtable.
// doubledHT := ht.Map(doubleValue)
// // doubledHT contains: {"apple": 10, "banana": 6, "cherry": 16}
func (hashtable *Hashtable[K, V]) Map(fn func(key K, value V) V) *Hashtable[K, V] {
for key, value := range *hashtable {
hashtable.Add(key, fn(key, value))
}
return hashtable
}
21 changes: 21 additions & 0 deletions hashtable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ func TestKeys(t *testing.T) {
}
}

// TestKeysFunc tests Hashtable.KeysFunc.
func TestKeysFunc(t *testing.T) {
// Create a new hashtable.
ht := make(hashtable.Hashtable[string, int])
Expand All @@ -596,3 +597,23 @@ func TestKeysFunc(t *testing.T) {
t.Errorf("Expected keys: %v, but got: %v", expectedKeys, keys)
}
}

// TestLength tests Hashtable.Length.
func TestLength(t *testing.T) {
// Create a new hashtable.
ht := make(hashtable.Hashtable[string, int])
ht["apple"] = 5
ht["banana"] = 3
ht["cherry"] = 8

// Get the length of the hashtable.
length := ht.Length()

// Expected length: 3
expectedLength := 3

// Verify that the obtained length matches the expected length.
if length != expectedLength {
t.Errorf("Expected length: %d, but got: %d", expectedLength, length)
}
}

0 comments on commit e144b90

Please sign in to comment.