To adapt the FilterValues function to work with map values instead of a slice, we need to:
- Accept a map as input, where the keys are of a comparable type (a requirement in Go for map keys).
- Extract the values of the map and apply the provided predicate.
- Return a slice of the values that satisfy the predicate.
The resulting function will be generic and will preserve the behavior of the original FilterValues function, but now operate on the values of a map rather than the elements of a slice.
✅ Final Implementation
func FilterMapValues[K comparable, V any](m map[K]V, predicate func(V) bool) []V {
result := make([]V, 0, len(m))
for _, value := range m {
if predicate(value) {
result = append(result, value)
}
}
return result
}
🔍 Explanation
K comparable: Ensures the map key type is compatible with Go's map syntax.
V any: Allows the map values to be of any type.
predicate func(V) bool: A function that takes a value and returns a bool indicating whether it should be included.
make([]V, 0, len(m)): Preallocates the result slice with the same capacity as the map, similar to the original function.
for _, value := range m: Iterates over the map values (ignoring the keys).
append: Adds the matching values to the result slice.
🧪 Example Usage
func main() {
m := map[string]int{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
}
filtered := FilterMapValues(m, func(v int) bool {
return v%2 == 0
})
fmt.Println(filtered) // Output: [2 4]
}
This version of the function maintains the same API design and behavior as the original FilterValues, but now works on map values, making it a natural extension for working with Go's map type.