| 84 | } |
| 85 | |
| 86 | func TestFilter(t *testing.T) { |
| 87 | t.Parallel() |
| 88 | |
| 89 | type testCase[T any] struct { |
| 90 | haystack []T |
| 91 | cond func(T) bool |
| 92 | expected []T |
| 93 | } |
| 94 | |
| 95 | { |
| 96 | testCases := []*testCase[int]{ |
| 97 | { |
| 98 | haystack: []int{1, 2, 3, 4, 5}, |
| 99 | cond: func(num int) bool { |
| 100 | return num%2 == 1 |
| 101 | }, |
| 102 | expected: []int{1, 3, 5}, |
| 103 | }, |
| 104 | { |
| 105 | haystack: []int{1, 2, 3, 4, 5}, |
| 106 | cond: func(num int) bool { |
| 107 | return num%2 == 0 |
| 108 | }, |
| 109 | expected: []int{2, 4}, |
| 110 | }, |
| 111 | } |
| 112 | |
| 113 | for _, tc := range testCases { |
| 114 | actual := slice.Filter(tc.haystack, tc.cond) |
| 115 | require.Equal(t, tc.expected, actual) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | { |
| 120 | testCases := []*testCase[string]{ |
| 121 | { |
| 122 | haystack: []string{"hello", "hi", "bye"}, |
| 123 | cond: func(str string) bool { |
| 124 | return strings.HasPrefix(str, "h") |
| 125 | }, |
| 126 | expected: []string{"hello", "hi"}, |
| 127 | }, |
| 128 | { |
| 129 | haystack: []string{"hello", "hi", "bye"}, |
| 130 | cond: func(str string) bool { |
| 131 | return strings.HasPrefix(str, "b") |
| 132 | }, |
| 133 | expected: []string{"bye"}, |
| 134 | }, |
| 135 | } |
| 136 | |
| 137 | for _, tc := range testCases { |
| 138 | actual := slice.Filter(tc.haystack, tc.cond) |
| 139 | require.Equal(t, tc.expected, actual) |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |