lo icon indicating copy to clipboard operation
lo copied to clipboard

Proposal: Iterate a map by sorted keys

Open leaanthony opened this issue 3 years ago • 1 comments

It is fairly common in code generation to sort the data before generating to make the output consistent for testing purposes. Currently, the only solution when using maps is to get the keys into a slice, sort the keys using slice sort, then iterate this new slice and pull out values from the map by key. If you have multiple nested maps (not uncommon) then this effort is duplicated. It would be amazing if there was a method to iterate maps by sorted key. Happy to make a PR for it if accepted. Thanks.

leaanthony avatar Mar 06 '23 09:03 leaanthony

I would still like to see this, I ran into this again today. For now I only needed it for string keys so I've created this:

// foreachKeySorted iterates over the items of a map with string keys, sorted by the key.
func foreachKeySorted[T any](m map[string]T, f func(string, T) error) error {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		if err := f(k, m[k]); err != nil {
			return err
		}
	}

	return nil
}

Maybe it can help someone that runs into this issue.

advdv avatar Mar 05 '24 12:03 advdv