2
0

maputil.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package maputil
  2. import "iter"
  3. // Map applies a transformation function to each value within a map to get a new map containing the
  4. // transformed values.
  5. func Map[K comparable, V any, T any](m map[K]V, transform func(V) T) map[K]T {
  6. result := make(map[K]T, len(m))
  7. for k, v := range m {
  8. result[k] = transform(v)
  9. }
  10. return result
  11. }
  12. // Flatten returns an iterator that will iterate over a nested map.
  13. func Flatten[Map ~map[T]Inner, Inner ~map[T]U, T comparable, U any](m Map) iter.Seq[U] {
  14. return func(yield func(U) bool) {
  15. for _, inner := range m {
  16. for _, value := range inner {
  17. if !yield(value) {
  18. return
  19. }
  20. }
  21. }
  22. }
  23. }
  24. // FlatMap returns an iterator that will iterate over a nested map, and apply a transformation to a different type.
  25. func FlatMap[Map ~map[T]Inner, Inner ~map[T]U, T comparable, U any, V any](m Map, transform func(U) V) iter.Seq[V] {
  26. return func(yield func(V) bool) {
  27. for _, inner := range m {
  28. for _, value := range inner {
  29. if !yield(transform(value)) {
  30. return
  31. }
  32. }
  33. }
  34. }
  35. }