diff --git a/pkg/fp/map.go b/pkg/fp/map.go new file mode 100644 index 0000000..3108749 --- /dev/null +++ b/pkg/fp/map.go @@ -0,0 +1,17 @@ +package fp + +import "encoding/json" + +func FromMap[T any](input map[string]any) (*T, error) { + in, err := json.Marshal(input) + if err != nil { + return nil, err + } + + out := new(T) + if err := json.Unmarshal(in, out); err != nil { + return nil, err + } + + return out, nil +} diff --git a/pkg/fp/map_test.go b/pkg/fp/map_test.go new file mode 100644 index 0000000..00dea64 --- /dev/null +++ b/pkg/fp/map_test.go @@ -0,0 +1,27 @@ +package fp_test + +import ( + "testing" + + "github.com/kaytu-io/kaytu-util/pkg/fp" + "github.com/stretchr/testify/require" +) + +func TestFromMap(t *testing.T) { + require := require.New(t) + + type student struct { + Name string `json:"name,omitempty"` + ID int `json:"id,omitempty"` + } + + input := map[string]any{ + "name": "Parham Alvani", + "id": 9231058, + } + + s, err := fp.FromMap[student](input) + require.NoError(err) + require.Equal("Parham Alvani", s.Name) + require.Equal(9231058, s.ID) +}