wk8 / go-ordered-map

Optimal implementation of ordered maps for Golang - ie maps that remember the order in which keys were inserted.
Apache License 2.0
532 stars 40 forks source link

Add hint on how to filter OrderedMaps to README #38

Open WilliamFrei opened 7 months ago

WilliamFrei commented 7 months ago

To filter elements from the OrderedMap, the most obvious approach would be the following:

for pair := om.Oldest(); pair != nil; pair = pair.Next() {
    if Predicate(pair.Value) {
        om.Delete(pair.Key)
    }
}

This does not work: It will only delete the first match.

It is also not possible to fix this in this repository, as the cause for this behaviour lies in the list implementation used.

The following code works:

for pair := om.Oldest(); pair != nil; {
    key, value := pair.Key, pair.Value
    pair = pair.Next()
    if Predicate(value) {
        om.Delete(key)
    }
}

The same problem occurs if the iteration order is reversed, and is also independent of the Predicate parameters (e.g. removing the first 10 or all elements with the first pattern will not work).

I suggest adding a hint on how to filter the OrderedMap with the second snippet to the README.

I can also create a PR if you do not have the time.