maputil.go 1.0 KB

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