iancoleman / orderedmap

orderedmap is a golang map where the keys keep the order that they're added. It can be de/serialized from/to JSON. It's based closely on the python collections.OrderedDict.
MIT License
356 stars 55 forks source link

Please provide a Values() method that returns the underlying Go map #24

Closed varunbpatil closed 1 year ago

varunbpatil commented 3 years ago

Hi,

First of all, many thanks for this code. It would be helpful if you can add a Values() method similar to the Keys() method to return the underlying Go map. Right now, I have to iterate over keys and get their value to construct a similar Go map.

I need the raw map, for example, to pass it to the mapstructure package to convert the map into a struct.

I'd be happy to create a PR.

Thanks.

zamicol commented 1 year ago

I think there was an attempt to do this, or so the tests seem to suggest:

https://github.com/iancoleman/orderedmap/blob/7c914fa9a8916d5034a6b55c92f606b35bc4e5ba/orderedmap_test.go#L63C1-L72C3

    // Keys method
    keys := o.Keys()
    expectedKeys := []string{
        "number",
        "string",
        "strings",
        "mixed",
    }
    for i, key := range keys {
        if key != expectedKeys[i] {
            t.Error("Keys method", key, "!=", expectedKeys[i])
        }
    }
    for i, key := range expectedKeys {
        if key != expectedKeys[i] {
            t.Error("Keys method", key, "!=", expectedKeys[i])
        }
    }

The second for loop is not meaningful. I'm assuming that it was meant for a values method. It's possible it was also copy-pasta.

As far as a solution, here's a simple Values method:

func (o *orderedMap) Values() []any {
    v := make([]any, len(o.keys))
    for i, k := range o.keys {
        v[i] = o.values[k]
    }
    return v
}

For a full implementation, that may be imported as a package, see

https://github.com/Cyphrme/OrderedMap

iancoleman commented 1 year ago

Thanks for the suggestion.

Implemented in https://github.com/iancoleman/orderedmap/commit/417c64442457548567e2ba59bcd91da5ae3e0b14