Skip to content

Commit

Permalink
feat: add generic function for from map
Browse files Browse the repository at this point in the history
  • Loading branch information
Parham Alvani committed Dec 28, 2023
1 parent b2f60ac commit 7691b45
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/fp/map.go
Original file line number Diff line number Diff line change
@@ -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
}
27 changes: 27 additions & 0 deletions pkg/fp/map_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 7691b45

Please sign in to comment.