Skip to content

Commit f9cff99

Browse files
authored
Merge pull request #1346 from ydb-platform/xslices
added xslices.Map and xslices.Filter
2 parents 17331d3 + d9f7608 commit f9cff99

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

internal/xslices/map.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package xslices
2+
3+
func Map[Key comparable, T any](x []T, key func(t T) Key) map[Key]T {
4+
m := make(map[Key]T, len(x))
5+
6+
for i := range x {
7+
m[key(x[i])] = x[i]
8+
}
9+
10+
return m
11+
}

internal/xslices/map_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package xslices
2+
3+
import (
4+
"strconv"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestMap(t *testing.T) {
11+
require.Equal(t,
12+
map[string]int{
13+
"1": 1,
14+
"2": 2,
15+
"3": 3,
16+
},
17+
Map([]int{1, 2, 3}, strconv.Itoa),
18+
)
19+
}

internal/xslices/split.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package xslices
2+
3+
func Filter[T any](x []T, filter func(t T) bool) (good, bad []T) {
4+
good = make([]T, 0, len(x))
5+
bad = make([]T, 0, len(x))
6+
7+
for i := 0; i < len(x); i++ {
8+
if filter(x[i]) {
9+
good = append(good, x[i])
10+
} else {
11+
bad = append(bad, x[i])
12+
}
13+
}
14+
15+
return good, bad
16+
}

internal/xslices/split_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package xslices
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/require"
7+
)
8+
9+
func TestFilter(t *testing.T) {
10+
good, bad := Filter([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, func(t int) bool {
11+
return t%2 == 0
12+
})
13+
require.Equal(t, []int{0, 2, 4, 6, 8}, good)
14+
require.Equal(t, []int{1, 3, 5, 7, 9}, bad)
15+
}

0 commit comments

Comments
 (0)