maputil_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package maputil
  2. import (
  3. "testing"
  4. )
  5. type set[T comparable] struct {
  6. m map[T]struct{}
  7. }
  8. func newSet[T comparable](values ...T) *set[T] {
  9. s := &set[T]{
  10. m: make(map[T]struct{}, len(values)),
  11. }
  12. for _, v := range values {
  13. s.m[v] = struct{}{}
  14. }
  15. return s
  16. }
  17. func (s *set[T]) contains(value T) bool {
  18. _, ok := s.m[value]
  19. return ok
  20. }
  21. func (s *set[T]) remove(value T) {
  22. delete(s.m, value)
  23. }
  24. func TestFlatten(t *testing.T) {
  25. m := map[string]map[string]int{
  26. "A": {
  27. "b": 1,
  28. "c": 2,
  29. "d": 3,
  30. },
  31. "B": {
  32. "e": 4,
  33. "f": 5,
  34. },
  35. "C": {
  36. "g": 6,
  37. "h": 7,
  38. "i": 8,
  39. "j": 9,
  40. },
  41. }
  42. expected := newSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
  43. flattened := Flatten(m)
  44. for value := range flattened {
  45. if !expected.contains(value) {
  46. t.Errorf("expected values did not contain the value: %d", value)
  47. }
  48. expected.remove(value)
  49. }
  50. }
  51. func TestAliasedMapFlatten(t *testing.T) {
  52. type IntMap map[string]int
  53. type StringIntMap map[string]IntMap
  54. m := StringIntMap(map[string]IntMap{
  55. "A": IntMap(map[string]int{
  56. "b": 1,
  57. "c": 2,
  58. "d": 3,
  59. }),
  60. "B": IntMap(map[string]int{
  61. "e": 4,
  62. "f": 5,
  63. }),
  64. "C": IntMap(map[string]int{
  65. "g": 6,
  66. "h": 7,
  67. "i": 8,
  68. "j": 9,
  69. }),
  70. })
  71. expected := newSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
  72. flattened := Flatten(m)
  73. for value := range flattened {
  74. if !expected.contains(value) {
  75. t.Errorf("expected values did not contain the value: %d", value)
  76. }
  77. expected.remove(value)
  78. }
  79. }
  80. func TestFlatMap(t *testing.T) {
  81. m := map[string]map[string]int{
  82. "A": {
  83. "b": 1,
  84. "c": 2,
  85. "d": 3,
  86. },
  87. "B": {
  88. "e": 4,
  89. "f": 5,
  90. },
  91. "C": {
  92. "g": 6,
  93. "h": 7,
  94. "i": 8,
  95. "j": 9,
  96. },
  97. }
  98. expected := newSet(2, 4, 6, 8, 10, 12, 14, 16, 18)
  99. flatMap := FlatMap(m, func(value int) int {
  100. return value * 2
  101. })
  102. for value := range flatMap {
  103. if !expected.contains(value) {
  104. t.Errorf("expected values did not contain the value: %d", value)
  105. }
  106. expected.remove(value)
  107. }
  108. }