golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.72k stars 17.63k forks source link

proposal: maps: add functions to filter and transform map values #70061

Closed pixel365 closed 2 hours ago

pixel365 commented 2 hours ago

Proposal Details

I propose to add the following general-purpose functions to the maps package:

// FilterFunc returns an iterator with filtered key-value pairs.
func FilterFunc[M ~map[K]V, K comparable, V any](m M, filter func(K, V) bool) iter.Seq2[K, V] {
    return func(yield func(K, V) bool) {
        for k, v := range m {
            if filter(k, v) {
                if !yield(k, v) {
                    return
                }
            }
        }
    }
}
// TransformValuesFunc modifies values ​​with a user-defined function.
func TransformValuesFunc[M ~map[K]V, K comparable, V any](m M, transform func(K, V) V) {
    for k, v := range m {
        m[k] = transform(k, v)
    }
}
gabyhelp commented 2 hours ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

seankhliao commented 2 hours ago

This is just xiter.Filter(f, maps.All(m)) and xiter.Map(f, maps.All(m)) from #61898 No need for specialized functions

seankhliao commented 2 hours ago

Duplicate of #61898