From 664542c32438498e71455761c242d3df991e88f7 Mon Sep 17 00:00:00 2001 From: Beorn Facchini Date: Fri, 8 Oct 2021 00:50:25 +1100 Subject: [PATCH] Add method to get key for a given value --- orderedmap.go | 9 +++++++++ orderedmap_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/orderedmap.go b/orderedmap.go index 2341f91..ac56dd7 100644 --- a/orderedmap.go +++ b/orderedmap.go @@ -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 { diff --git a/orderedmap_test.go b/orderedmap_test.go index dfc50f1..188dc8f 100644 --- a/orderedmap_test.go +++ b/orderedmap_test.go @@ -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", @@ -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{ @@ -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) {