diff --git a/hashtable.go b/hashtable.go index a92f2dc..5254665 100644 --- a/hashtable.go +++ b/hashtable.go @@ -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 +} diff --git a/hashtable_test.go b/hashtable_test.go index 5c3a3f8..a7b035a 100644 --- a/hashtable_test.go +++ b/hashtable_test.go @@ -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]) @@ -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) + } +}