Commit 4b27adc

mo khan <mo@mokhan.ca>
2025-04-30 18:51:08
feat: add generate New[T] to initialize any type
1 parent 0772312
Changed files (2)
pkg/x/types.go
@@ -2,6 +2,8 @@ package x
 
 import "reflect"
 
+type Option[T any] func(T) T
+
 func Default[T any]() T {
 	item := Zero[T]()
 
@@ -12,6 +14,14 @@ func Default[T any]() T {
 	return item
 }
 
+func New[T any](options ...Option[T]) T {
+	item := Default[T]()
+	for _, option := range options {
+		item = option(item)
+	}
+	return item
+}
+
 func Zero[T any]() T {
 	var item T
 	return item
pkg/x/types_test.go
@@ -2,6 +2,7 @@ package x
 
 import (
 	"net/http"
+	"net/url"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -28,7 +29,7 @@ func TestTypes(t *testing.T) {
 	})
 
 	t.Run("Default", func(t *testing.T) {
-		t.Run("returns nil", func(t *testing.T) {
+		t.Run("returns a new instance", func(t *testing.T) {
 			result := Default[*http.Client]()
 
 			assert.NotNil(t, result)
@@ -52,6 +53,46 @@ func TestTypes(t *testing.T) {
 		})
 	})
 
+	t.Run("New", func(t *testing.T) {
+		t.Run("returns a new instance", func(t *testing.T) {
+			result := New[*http.Client]()
+
+			assert.NotNil(t, result)
+			assert.True(t, IsPtr(result))
+		})
+
+		t.Run("configures the new instance", func(t *testing.T) {
+			option := func(r *http.Request) *http.Request {
+				r.Method = "GET"
+				return r
+			}
+
+			result := New[*http.Request](option)
+
+			assert.NotNil(t, result)
+			assert.True(t, IsPtr(result))
+			assert.Equal(t, "GET", result.Method)
+		})
+
+		t.Run("configures a new instance with multiple options", func(t *testing.T) {
+			option := func(r *http.Request) *http.Request {
+				r.Method = "GET"
+				return r
+			}
+			otherOption := func(r *http.Request) *http.Request {
+				r.URL = Must(url.Parse("/example"))
+				return r
+			}
+
+			result := New[*http.Request](option, otherOption)
+
+			assert.NotNil(t, result)
+			assert.True(t, IsPtr(result))
+			assert.Equal(t, "GET", result.Method)
+			assert.Equal(t, "/example", result.URL.Path)
+		})
+	})
+
 	t.Run("IsSlice", func(t *testing.T) {
 		t.Run("returns true", func(t *testing.T) {
 			assert.True(t, IsSlice(Default[[]string]()))