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

Add method to get key for a given value #27

Open
wants to merge 1 commit 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
9 changes: 9 additions & 0 deletions orderedmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ func (o *OrderedMap) Get(key string) (interface{}, bool) {
return val, exists
}

func (o *OrderedMap) GetKey(value interface{}) (string, bool) {
for _, key := range o.keys {
if o.values[key] == value {
return key, true
}
}
return "", false
}

func (o *OrderedMap) Set(key string, value interface{}) {
_, exists := o.values[key]
if !exists {
Expand Down
17 changes: 17 additions & 0 deletions orderedmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,20 @@ func TestOrderedMap(t *testing.T) {
if v.(int) != 3 {
t.Error("Set number")
}
k, _ := o.GetKey(3)
if k != "number" {
t.Error("Get number key")
}
// string
o.Set("string", "x")
v, _ = o.Get("string")
if v.(string) != "x" {
t.Error("Set string")
}
k, _ = o.GetKey("x")
if k != "string" {
t.Error("Get string key")
}
// string slice
o.Set("strings", []string{
"t",
Expand Down Expand Up @@ -52,6 +60,10 @@ func TestOrderedMap(t *testing.T) {
if v.(int) != 4 {
t.Error("Override existing key")
}
k, _ = o.GetKey(4)
if k != "number" {
t.Error("Get number key")
}
// Keys method
keys := o.Keys()
expectedKeys := []string{
Expand Down Expand Up @@ -80,6 +92,11 @@ func TestOrderedMap(t *testing.T) {
if ok {
t.Error("Delete did not remove 'strings' key")
}
o.Delete("number")
_, ok = o.GetKey(4)
if ok {
t.Error("Delete did not remove 'number' key")
}
}

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