Skip to content

Commit

Permalink
Add keys values to bimap (#2754)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Feb 20, 2024
1 parent 1c92a17 commit e0738a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
13 changes: 13 additions & 0 deletions utils/bimap/bimap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"encoding/json"
"errors"

"golang.org/x/exp/maps"

"github.com/ava-labs/avalanchego/utils"
)

Expand Down Expand Up @@ -110,6 +112,17 @@ func (m *BiMap[K, V]) DeleteValue(val V) (K, bool) {
return key, true
}

// Keys returns the keys of the map. The keys will be in an indeterminate order.
func (m *BiMap[K, _]) Keys() []K {
return maps.Keys(m.keyToValue)
}

// Values returns the values of the map. The values will be in an indeterminate
// order.
func (m *BiMap[_, V]) Values() []V {
return maps.Values(m.keyToValue)
}

// Len return the number of entries in this map.
func (m *BiMap[K, V]) Len() int {
return len(m.keyToValue)
Expand Down
12 changes: 11 additions & 1 deletion utils/bimap/bimap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,23 +309,33 @@ func TestBiMapDeleteValue(t *testing.T) {
}
}

func TestBiMapLen(t *testing.T) {
func TestBiMapLenAndLists(t *testing.T) {
require := require.New(t)

m := New[int, int]()
require.Zero(m.Len())
require.Empty(m.Keys())
require.Empty(m.Values())

m.Put(1, 2)
require.Equal(1, m.Len())
require.ElementsMatch([]int{1}, m.Keys())
require.ElementsMatch([]int{2}, m.Values())

m.Put(2, 3)
require.Equal(2, m.Len())
require.ElementsMatch([]int{1, 2}, m.Keys())
require.ElementsMatch([]int{2, 3}, m.Values())

m.Put(1, 3)
require.Equal(1, m.Len())
require.ElementsMatch([]int{1}, m.Keys())
require.ElementsMatch([]int{3}, m.Values())

m.DeleteKey(1)
require.Zero(m.Len())
require.Empty(m.Keys())
require.Empty(m.Values())
}

func TestBiMapJSON(t *testing.T) {
Expand Down

0 comments on commit e0738a5

Please sign in to comment.