소스 검색

Merge pull request #47209 from corhere/sliceutil-map

internal/sliceutil: add utilities to map values
Sebastiaan van Stijn 1 년 전
부모
커밋
86198815a2
2개의 변경된 파일67개의 추가작업 그리고 0개의 파일을 삭제
  1. 18 0
      internal/sliceutil/sliceutil.go
  2. 49 0
      internal/sliceutil/sliceutil_test.go

+ 18 - 0
internal/sliceutil/sliceutil.go

@@ -11,3 +11,21 @@ func Dedup[T comparable](slice []T) []T {
 	}
 	}
 	return out
 	return out
 }
 }
+
+func Map[S ~[]In, In, Out any](s S, fn func(In) Out) []Out {
+	res := make([]Out, len(s))
+	for i, v := range s {
+		res[i] = fn(v)
+	}
+	return res
+}
+
+func Mapper[In, Out any](fn func(In) Out) func([]In) []Out {
+	return func(s []In) []Out {
+		res := make([]Out, len(s))
+		for i, v := range s {
+			res[i] = fn(v)
+		}
+		return res
+	}
+}

+ 49 - 0
internal/sliceutil/sliceutil_test.go

@@ -0,0 +1,49 @@
+package sliceutil_test
+
+import (
+	"net/netip"
+	"strconv"
+	"testing"
+
+	"github.com/docker/docker/internal/sliceutil"
+)
+
+func TestMap(t *testing.T) {
+	s := []int{1, 2, 3}
+	m := sliceutil.Map(s, func(i int) int { return i * 2 })
+	if len(m) != len(s) {
+		t.Fatalf("expected len %d, got %d", len(s), len(m))
+	}
+	for i, v := range m {
+		if expected := s[i] * 2; v != expected {
+			t.Fatalf("expected %d, got %d", expected, v)
+		}
+	}
+}
+
+func TestMap_TypeConvert(t *testing.T) {
+	s := []int{1, 2, 3}
+	m := sliceutil.Map(s, func(i int) string { return strconv.Itoa(i) })
+	if len(m) != len(s) {
+		t.Fatalf("expected len %d, got %d", len(s), len(m))
+	}
+	for i, v := range m {
+		if expected := strconv.Itoa(s[i]); v != expected {
+			t.Fatalf("expected %s, got %s", expected, v)
+		}
+	}
+}
+
+func TestMapper(t *testing.T) {
+	s := []string{"1.2.3.4", "fe80::1"}
+	mapper := sliceutil.Mapper(netip.MustParseAddr)
+	m := mapper(s)
+	if len(m) != len(s) {
+		t.Fatalf("expected len %d, got %d", len(s), len(m))
+	}
+	for i, v := range m {
+		if expected := netip.MustParseAddr(s[i]); v != expected {
+			t.Fatalf("expected %s, got %s", expected, v)
+		}
+	}
+}